Friday 15 March 2013

What is the purpose of finalisation?

What is the purpose of finalisation? 

Finalization was meant to clean up resources acquired by the object 
(not memory, but other resources, e.g. file handles, ports, DB connections etc.). 

Finalization is a facility provided by Java for classes who
use native resources to clean up before the objects are
garbage collected.

Since native resources or allocations are beyond the control
of Java's garbage collector, the responsibility of cleaning
up that native allocations falls on the object's
finalization code which should ideally initiate quick clean up
operations and free any native memory it has allocated.

If finalization is not done, then the native resources would
be left in the memory even after thier related Java
instances have been removed by the Java's GC. Hence it is an
invaluable feature. The garbage collector is working automatically in the 
background (although it can be explicitly invoked, but the need for this should be rare).

But it needs to be used with caution as finalization
consumes more processing by Java



Blog Author: Vijay Kumar

Go to: Coding Problem Solutions


No comments: