r/programming • • Dec 25 '17

How Memory Leaks Happen in a Java Application

https://stackify.com/memory-leaks-java/
36 Upvotes

10 comments sorted by

12

u/inmatarian Dec 25 '17

The hashCode and equals one, and using them in maps, is the not-obvious one.

7

u/ForeverAlot Dec 26 '17

That's not a leak, it's a fundamental logic error. The program is broken not because it consumes infinite memory but because it does entirely the wrong thing.

3

u/inmatarian Dec 26 '17

Describing away all bugs as logic errors where the program does the entirely wrong thing isn't exactly helpful. We categorize typical bugs for the reason of cataloging typical solutions. "Memory Leaking" is the type of bug your program is showing symptom of, and knowing that misuse of hashmaps is one possible diagnosis is very useful.

Failing to call free() in C is also writing an incorrect program.

1

u/ForeverAlot Dec 26 '17

Granted, but the example reads as if overriding hashCode and equals on types put into a set solves a problem; that it's technically necessary; or even that it's an error to fail to do so. None of those are true. You override hashCode and equals iff you can provide more meaningful implementations than the (perfectly sensible and completely correct) default ones.

There is another case very closely related to example 2.5 but it's just the generalised form of example 2.1: long-lived collections holding onto references long past their relevance, for example static fields or fields in effectively-singleton instances. That's a perfect case for WeakReference or something like Guava's Cache but it has nothing to do with equality tests.

2

u/pkulak Dec 26 '17

Pretty obvious that something terrible will happen though.

2

u/tqn3 Dec 25 '17

good post...thanks

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

u/[deleted] Dec 27 '17

maybe I’m dumb but doesn’t try-with-resources do this?