– This week decide to do a explanation of why picking Files.newOutputStream instead of FileOutputStream. The syntax is nearly identical, however performance won’t be the same. Different would be list below, following are the syntax of both method.
As some of you guys may claver enough to spot the different. Which is OutputStream is assigned by Files classes, which is a singleton class and FileOutputStream is the result of New FileOutputStream. Yup both of them works fine and used for ages by millions of businesss logic and on production every day. Why consider to switch? Yup that’s totally fine when processing file i/o operation, operation that wouldn’t much computation and application terminate straight away. However the problem kick in when application is long-life one and heavy I/O operation? New FileOutputStream is created every-time when new file I/O, which mean no matter how light does the FileOutput Stream instance is, it gonna occupied resources and only be free after 1 GC operation.
Just imagine that thousands of File I/O need to be processed in a second. And as the business nature needed, GC operation is scheduled to a relative long period of time, then what would happen? Thousands of FileOutputStream would be cleared and flushed only GC proceeded as FileOutputStream implemented Finalize( ) method. It would end up causing long time of clear those final reference in order to release the resources. Then why don’t stop it from creation?
By obtaining a OutputStream by Files classes, no new instance is needed as Files classes is singleton and only one copy is copied into heap. Which skip the step of New FileOutputStream ( )
– Why create it if gonna be destroyed soon?