In the Java object lifecycle, the finalize
method for an instance is called after the garbage collector has determined that the
instance can be removed from the object heap. Therefore, it is unnecessary to implement a finalizer to set instance fields explicitly to
null
to tell the garbage collector that the instance no longer needs them.
In the worst case, implementing finalize
is even counterproductive because it might accidentally create new references from other
(living) objects on the heap to the collectible instance, thus, reviving it.
Important note about finalizers:
There are no guarantees when the Java Runtime will call the finalize
method or whether it will be called at all.
Using finalizers is, therefore, a bad practice. They should never be used to free resources, such as closing streams, freeing locks, or freeing
native system resources. Consider other freeing mechanisms instead, such as an explicit close
, unlock
, or free
method in your class.