Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • JAVA Garbage Collection and finalize() method

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 70
    Comment on it

    Whenever an object is created using the new keyword in the memory, then a constructor is called to initialize the the object. Afterwards when the scope of the object comes to end the memory allocated required to be reclaimed at the runtime, then only the role of the garbage collection starts.

    The Garbage Collection is the process of destroying the allocated memory of an object after its scope ends.

    Whenever the object is not required any more it must be removed from the memory to reuse the memory. The process of removing unwanted memory is managed by garbage collection in java but in C they are performed manually by using destructors, also there is a function in C free() which does the same and in C++ delete() is the function.


    finalize() method In Java:


    The finalize() method is a non-static method of java.lang.Object class which is invoked every time before the Garbage Collection operation is done on object. The main aim of the method is to perform cleanup processing. The method is available for all the object created with the new keyword.


    Note: The Garbage collector collects all those objects in the java program which are declared using the new keyword. If an object is created without new keyword then we need to call Finalize() thread to perform the cleanup.


    Example of GC in JAVA


       public class TestGC{  
          public void finalize(){System.out.println("object is garbage collected");}  
              public static void main(String args[]){  
                          TestGC1 s1=new TestGC1();  
                          TestGC1 s2=new TestGC1();  
                          s1=null;  
                          s2=null;  
                         System.gc();  
               }  
         }
    

    Output
    object is garbage collected
    object is garbage collected

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: