Previous | Home | Next |
In java if an object has no object references pointing to it, can be deleted by the garbage collector to regain the memory. On the other hand, if an object has a finalize() method then it will be executed before regaining the memory in order to give the object a last chance to clean up itself i.e. to release all the resources that the object was using.
The finalize() method is inherited from the Object class by any class you define. The syntax of the finalize() method declaration is shown below,
protected void finalize()
Inside this finalize() method you must specify the actions that are needed to be performed before an object is recycled. The finalize() is only called just prior to garbage collection to if any resource was left to be released .It is advised that not use finalize() method just to be on a safer side. The program must release the resources in program itself, since garbage collectors run is not guaranteed, so finalize() execution will also not be guaranteed.
The Java programming language specifies that the finalize() method will be called before the object memory is reclaimed, but it does not guarantee exactly when it will happen. Note that the finalize() method which a class inherited does not do anything,thus, if you want your object to clean up itself, you have to override the finalize() method.
Also remember that, the finalize() method is never invoked more than once by a Java virtual machine for any given object. Generally, it is considered a good programming practice to invoke the finalize() of the superclass, i.e.,
protected void finalize() { super.finalize(); // some other logic }
The following code snippet will guide you how to use finalize() method during the garbage collection,
Example
Java Tutorialslass UsingFinalize { public static void main(String[] args) { Runtime rt = Runtime.getRuntime(); System.out.println("Total available memory:"+rt.totalMemory()); System.out.println("Available Free Memory: " + rt.freeMemory()); for(int j=0; j<1000; j++ ) { FinalizeMethod obj = new FinalizeMethod(j); } System.out.println("Free Memory before call to gc(): " + rt.freeMemory()); System.runFinalization(); System.gc(); System.out.println(" Free Memory after call to gc(): " + rt.freeMemory()); } } Java Tutorialslass FinalizeMethod { String str; int id; FinalizeMethod(int id) { this.str = new String("r4r tefsoft solutions"); this.id = id; } protected void finalize() { System.out.println("FinalizeMethod object " + id + " has been finalized."); } }
Previous | Home | Next |