Avoid finalizers and cleaners

There is a mechanism in Java which allows running a certain code on object destruction. Something in a way like a C++ destructor method. However, due to java memory design and implementation of garbage collection in different JVMs, you should never rely on it. You are not guaranteed when the “destructor” method will be called, if ever!

Just as a reference – the mechanism in question is the Finalizer or Cleaner. Please do not use them for anything more than a backup mechanism, but do not rely on them being executed, especially in a timely manner.

A much better technique for the objects to clean up after themselves – clean up the resources, close the connections – is to use try-with-resources statement.

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)