Wednesday, June 22, 2016

How to call a finalize method with different ways


To  call a finalize method from a code , we have different ways.

There are different ways to call a Garbage Collector to remove the non reference object, but we can't say exact what time will it remove the object from the memory.
Below are the following few ways to call the garbage collector.

1. System.gc():

  Example :  
                     Class Test{
                           public static void main(String[] args{
                                 Test t = new Test();
                                System.gc();
                           }
                       }

2. Object reference of your class dot finalize() method
   
      Example :  
                     Class Test{

                           public static void main(String[] args{
                           
                                 Test t = new Test();
                                  t.finalize();//Here we are calling garbage collector by using the finalize method
                           }
                       }
3. System.runFinalization():
 
This will tell the Garbage Collector to give me preference to remove  the objects
Example:

       public static void main(String args[]){
Test t=new Test();
 t.setName("ganesh");
System.runFinalization();
 System.out.println("Name is :"+t.getName());

}

No comments:

Post a Comment