Sunday, June 22, 2014

Garbage Collection

Garbage collection in java |  java garbage collection | what is garbage collection

Garbage collection is the process or feature of Java, in which Java run time environment automatically destroy the objects created and release their memory when Java run time environment determines that they are no longer needed. And the memory occupied by that object can be released and used by another object.
So we can say that garbage collection in java involves the following activities: -
  • Monitoring the objects and determine when they are not in use
  • Destroy objects that are no longer use and release the resource

How can an object become eligible for garbage Collection: -

An object becomes eligible for garbage collection when the following condition arises: -
  • Nulling a reference: - when an object is to set the reference variable that refers to the object to null.
Example a= new Example();
a= null;
  • Reassigning a reference variable: - when an object is set the reference variable that refer to another object.
Example a= new Example();
Example b= new Example();
a= b;
  • Isolating a reference: - when valid references objects become eligible for garbage collection, because there are no longer use of those objects.

Methods used by Garbage Collector: -

  • finalize() method: - The finalize() method is invoke each time before the object is garbage collected. i.e. the garbage collector gives the opportunity to object to clean up itself. This method is define as following :
protected void finalize()    
{}
                       And this process is called finalization.
  • gc() method: - We can run garbage collector explicitly by calling the gc() method. To run the garbage collector explicitly, we need following mechanism:
    • Create an object of the java run time class as follow:
    Runtime rt= Runtime.getRuntime();
    • Invoke the gc() method
      rt.gc();

No comments:

Post a Comment