The finalize() method is equivalent to a destructor of C++. When the job of an object is over, or to say, the object is no more used in the program, the object is known as garbage. The process of removing the object from a running program is known as garbage collection.Garbage collection frees the memory and this memory can be used by other programs or the same program further in its execution. Before an object is garbage collected, the JRE (Java Runtime Environment) calls the finalize() method. finalize() method can be best utilized by the programmer to close the I/O streams, JDBC connections or socket handles etc.
Following is the method signature as defined in Object class.
protected void finalize( ) throws Throwable
Notice, the finalize() method is declared as protected. The following program illustrates the usage of finalize() method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
public class Demo
{
static Demo d1, d2 ;
public void show( )
{
System.out.println("Hello 1");
}
protected void finalize( ) throws Throwable
{
if(d1 != null)
{
System.out.println("d1 object is not eligible for garbage collection and is still active");
d1 = null;
if (d1 == null)
System.out.println("d1 is not referenced and getting removed from memory");
}
if(d2 != null)
{
System.out.println("d2 object is not eligible for garbage collection and is still active");
d2 = null;
if(d2 == null)
System.out.println("d2 is not referenced and getting removed from memory");
}
super.finalize( );
}
public static void main( String args[])
{
d1 = new Demo();
d2 = new Demo();
d1.show();
d2.show( );
System.runFinalizersOnExit(true);
}
}
|
When d1 is not equal to null means it is still used in the program; there by println() method is executed.
d1 = null;
if (d1 == null)
d1 object is made null, that is, the d1 object is not referencing any data in the table. It is eligible for garbage collection and thereby the println() method is executed.
super.finalize() method calls finalize() method on the super class objects, if any exist. Garbage collection or finalize() method can not be forced to happen as garbage collection is an implicit behavior of JVM. Different JDKs come with different algorithms of garbage collector, and for this reason, we cannot exactly predict when the garbage collection takes place. But still programmer can advise the garbage collection to take place by calling the following methods; remember it is only an advice but not sure it will happen.
System class comes with the following two methods for garbage collection.
- System.runFinalization( ): removes all objects ready of garbage collection.
- System.runFinalizersOnExit(true): advice to call finalize() method before garbage collection. This method is deprecated in JDK 1.2.
No comments:
Post a Comment