Eliminate obsolete objects references

Java is a garbage-collected language. That means, that objects with no reference to them are cleared automatically. But it doesn’t make it a memory-leak free! Nulling the object to garbage-collect it should be an exception, not a norm. However, you still need to think about how the garbage collector works and how to design your program in order to help it operate.

One of the main sources of memory leakage can be storing the objects in a collection and managing its life cycle manually. Good solution to this problem is using the provided collection classes or frameworks – why should you reinvent the wheel. Also, please remember to always properly override hashCode() if you need to change the equals() method. Failing to do so can result in objects lost in a hash map!

Another scenario that comes to mind is caching. Some objects stored in cache tend to stay there forever. A remedy for this might me use of a WeakHashMap. A weak hash map stores the object as long as there are external references to the key. If the only reference to the key is the one held by the map itself – the key-pair value is marked for garbage collection.

The last one mentioned in Effective Java is listener pattern. when listeners are registered, but never explicitly deregistered. The book also provides a solution – use weak references.

This post is based on Joshua Bloch Effective Java Third Edition (get it on Amazon: https://www.amazon.com/Effective-Java-3rd-Joshua-Bloch/dp/0134685997)