What is the purpose of finalization in Java?

user244333 picture user244333 · Mar 15, 2010 · Viewed 25.1k times · Source

My understanding of finalization is this:

To clean up or reclaim the memory that an object occupies, the Garbage collector comes into action. (automatically is invoked?)

The garbage collector then dereferences the object. Sometimes, there is no way for the garbage collector to access the object. Then finalize is invoked to do a final clean up processing after which the garbage collector can be invoked.

Is this an accurate description of finalization?

Answer

Péter Török picture Péter Török · Mar 15, 2010

The garbage collector is working automatically in the background (although it can be explicitly invoked, but the need for this should be rare). It basically cleans up only objects which are not referenced by other objects (granted, the full picture is more complicated, but this is the basic idea). So it does not change any references in any live objects. If an object can not be accessed from any live object, this means that it can be safely garbage collected.

Finalization was meant to clean up resources acquired by the object (not memory, but other resources, e.g. file handles, ports, DB connections etc.). However, it did not really work out :-(

  • it is unpredictable when finalize() will be called
  • in fact, there is no guarantee that finalize() will be called ever!

So even if it were guaranteed to be called, it would not be a good place to release resources: by the time it is called to free up all the DB connections you have opened, the system may have run out of free connections completely, and your app does not work anymore.