Do unclosed streams cause memory leaks in java?

前端 未结 3 1721
忘了有多久
忘了有多久 2020-12-03 05:35

I believe open streams cause memory leak in java (at least java 1.6 and earlier did had this problem).

But, while searching (even here), I found some people agreein

3条回答
  •  一整个雨季
    2020-12-03 06:15

    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.

提交回复
热议问题