Reputation: 81
I was using soanr to check my java code, and one issue shows that ,we should use java.nio.file.Files.newInputStream(myfile.toPath()) instead of new FileInputStream(file). And the sonar description is :
This method creates and uses a java.io.FileInputStream or java.io.FileOutputStream object. Unfortunately both of these classes implement a finalize method, which means that objects created will likely hang around until a full garbage collection occurs, which will leave excessive garbage on the heap for longer, and potentially much longer than expected. Java 7 introduced two ways to create streams for reading and writing files that do not have this concern. You should consider switching from these above classes to InputStream is = java.nio.file.Files.newInputStream(myfile.toPath()); OutputStream os = java.nio.file.Files.newOutputStream(myfile.toPath());
My question is, is it right?
Upvotes: 6
Views: 5053
Reputation: 5131
That is a dense statement. Thus, it might be worth to break it into smaller chunk. First thing first,
This method creates and uses a java.io.FileInputStream or java.io.FileOutputStream object. Unfortunately both of these classes implement a finalize method
This is true and false. the function itself has been marked as deprecated since java 9. And, it has been removed 5 months ago. So, depending on java version you used. It probably still exists (assuming most people are still using java 8). See this commit for more information.
which means that objects created will likely hang around until a full garbage collection occurs, which will leave excessive garbage on the heap for longer, and potentially much longer than expected
Yeah, because, finalize
function is invoked after GC. Then, most likely, the object would linger on the heap longer. See javadoc for finalize
function here.
Java 7 introduced two ways to create streams for reading and writing files that do not have this concern
True, I have checked the source code in openjdk repo. And, I don't see the implementation of classes that those two functions use implement the finalize
method. See the repo here
Upvotes: 6