Do unclosed streams cause memory leaks in java?

It’s important to be precise in the use of the term ‘memory leak’ with respect to Java.

In Java, a memory leak happens when your code holds a reference permanently, so that some object is never garbage collected.

Failing to close a stream is not a memory leak in this sense. Streams that have native resources have finalizers; the GC will eventually close them down. Unless you hold a reference to the unclosed stream it isn’t a leak.

However, there are other kinds of leaks besides memory leaks. Most operating systems limit the number of open files. If you fail to close your streams, the GC may take a very long time to close them for you; the net result may be that you run out of system file descriptors and your code fails to open one more file. Some people will call this a leak, but it’s not accuracy to call it a memory leak.

Leave a Comment