
1. Null out references once they become obsolete
The Figure 1. code has a possible memory leak, as the objects popped off from the stack will not be garbage collected.
This is because the stack will maintain obsolete references (References that will never be dereferenced again) to the objects that are residing over than size(index) of the array. This causes Garbage Collector not to be able to collect the memories that were captured by them.
To solve this issue, updating the pop() method as below Figure 2. is required, which removes the reference by setting the element as null.

2. Nulling out object references should be the exception rather than norm.
Figure 2 would definitely resolve the issue, but nulling out is not just the perfect solution that we can use any time. For better solution, it is recommended to narrow the scope of the variable as much as possible.
If that so, in which case should we null out the references then?
In places like Stack class which manages its own memory, we should inform Garbage Collector about the obsolete reference so that the GC can collect the memory back.
3. Cache can be vulnerable to memory leak
Putting object references into a cache and not referencing causes a possible memory leak.
To avoid this, it is recommended to use WeakHashMap for representing a cache, which will automatically remove the obsolete references. Or we can use a background thread like ScheduledThreadPoolExecutor which would clean up the entries that becomes less valuable over time.
4. Creating listeners and callbacks may leave out obsolete references
If we only implement listeners and callbacks without deregistering them, they can occupy memories as well.
To avoid this, store callbacks into weak reference as the key of WeakHashMap.

Leave a comment