Are dereferenced open streams implicitly closed?
August 28, 2009 8:32 AM
Subscribe
Java filter: Are dereferenced InputStreams implicitly closed?
InputStream s;
s = new InputStream(filename1);
... // filename1 is read and used.
// Ok, I'm done with filename1, but I want to reuse s to open filename2
s = new InputStream(filename2);
Does calling a new instance of s implicitly call s.close() to close the filename1 stream before opening the new stream?
Or is filename1 stream just now dereferenced open stream?
I ask because I ran into the "too many files open" exception when I ran my program on Fedora. So, while I was in the process of cleaning up my code and making sure I closed all InputStreams, it dawned on me that reusing an InputStream variable without first explicitly calling close() might not close the old stream. Is this true?
Also, I'm aware that you can increase the # of open files limit in Linux, but I'd rather stick to good coding practices instead of a band-aid solution.
posted by nikkorizz to computers & internet (5 comments total)
Assuming these are FileInputStreams, the garbage collector will call dispose() on them when it destroys them, but there is no guarantee that the garbage collector will ever reclaim the first input stream. And in practice, it probably will not unless the JVM gets low on memory.
posted by Khalad at 8:39 AM on August 28