Sponsored Link •
In this article, I look at a fundamental issue with network-mobile code: clients (such as Jini browsers) that load objects of which they have no prior knowledge cannot invoke cleanup methods on those objects. I propose a solution to this problem, using the
finalize()method declared in class
In May 1998, I published "Object finalization and cleanup" in my Design Techniques column of JavaWorld. In this article, I gave advice on designing the end of object lifetimes. In particular, I tried to answer the question, "What the heck are finalizers for?"
The contract of finalize()
A finalizer is a Java instance method named
finalize() that returns
void and takes no arguments.
Object declares such a method with the
protected permission. The Java specifications make the following promise about finalizers:
Before reclaiming the memory occupied by an object that has a finalizer, the garbage collector will invoke that object's finalizer.
The javadoc page for class
Object says the following about
finalize() method's purpose:
The general contract of
finalizeis that it is invoked if and when the Java virtual machine has determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, except as a result of an action taken by the finalization of some other object or class that is ready to be finalized. The
finalizemethod may take any action, including making this object available again to other threads; the usual purpose of
finalize, however, is to perform cleanup actions before the object is irrevocably discarded. For example, the finalize method for an object that represents an input/output connection might perform explicit I/O transactions to break the connection before the object is permanently discarded.