r/programming • u/javinpaul • Dec 25 '17
How Memory Leaks Happen in a Java Application
https://stackify.com/memory-leaks-java/2
2
u/kcin Dec 26 '17
Why can't the JVM close streams automatically when the function exits and the variable refering to the stream goes out of scope? When there are no more variables pointing to the stream then it can be closed, can't it?
3
u/selonus Dec 26 '17
In theory streams could be closed in the finalize() but one problem is that the GC doesn't run deterministically, yet the caller needs to have control over cleaning up system resources.
The jvm also does escape analysis for local variables, and it could theoretically auto close streams that never escape a function, but this is only a specific optimization and not the general case.
1
12
u/inmatarian Dec 25 '17
The hashCode and equals one, and using them in maps, is the not-obvious one.