-
Notifications
You must be signed in to change notification settings - Fork 0
Memory leak in Java
The Java garbage collector works the other way round, as you might think, meaning it is not looking for garbage, but looking for valuable objects. The garbage collector first marks the objects that cannot be deleted and then deletes all the others in a second step. Objects that are accessible through references stored in the stack should not be deleted.
So what are the typical sources of a memory leak?
Objects referenced by static member variables are never released. It is dangerous to store references in an array (e.g., Object []) and handle the size of the array ourselves, so care must be taken to reset references that are no longer used.
Not closing file streams may cause memory leaks as well. Always use the try-with-resource pattern when dealing with streams!
In the case of possible cache implementations, care must be taken to delete references to objects that are no longer needed.
In case of an Observer pattern, care must be taken to ensure that the terminating objects unregister itself, otherwise they will also result in a memory leak. See also The lapsed listener problem on Wikipedia.
TBD
This happens in the case of non-static inner classes. For initialization, these inner classes always require an instance of the enclosing class.
Every non-static inner class has, by default, an implicit reference to its containing class. If we use this inner class' object in our application, then even after our containing class' object goes out of scope, it will not be garbage collected.
- If the inner class doesn't need access to the containing class members, consider turning it into a static class
- Non-static inner classes should be private