Thursday, October 28, 2021

Cleaning Up Unused Objects (Garbage Collection)

Some object-oriented languages require keeping track of all the objects that are created, and they  explicitly destroyed when they are no longer needed. Managing memory explicitly is tedious and error-prone.

The Java platform allows to create objects as wanted, and no need to worry about destroying them. The Java runtime environment deletes objects when it determines that they are no longer being used. This
process is called garbage collection.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.

An object is eligible for garbage collection when there are no more references to that object. References that are held in a variable are usually dropped when the variable goes out of scope.

An object can be unreferenced by:

  • By nulling the reference

Employee e=new Employee();  

e=null;  

  • By assigning a reference to another

Employee e1=new Employee();  

Employee e2=new Employee();  

e1=e2;//now the first object referred by e1 is available for garbage collection  

  • By anonymous object etc.

new Employee();  

Finalization

The Garbage collector of JVM collects only those objects that are created by new keyword. So if any object created without new, finalize method is used to perform cleanup processing (destroying remaining objects).

Before an object gets garbage-collected, the garbage ollector gives the object an opportunity to clean up after itself through a call to the object's finalize method. The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This process is known as finalization.

The finalize method is a member of the Object class, which is the top of the Java platform's class hierarchy.

This method is defined in Object class as: 

protected void finalize(){}  

A class can override the finalize method to perform any finalization necessary for objects of that type.

gc() method

The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.

Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the finalize() method before object is garbage collected.


public static void gc(){}  

Example:

public class TestGarbage{  

 public void finalize(){

System.out.println("object is garbage collected");

}  

public static void main(String args[]){  

  TestGarbage s1=new TestGarbage();  

  TestGarbage s2=new TestGarbage();  

  s1=null;  

  s2=null;  

  System.gc();  

 }  

0 comments:

Post a Comment

Data Structures with C++



NET/SET/CS PG



Operating Systems



Computer Networks



JAVA



Design and Analysis of Algorithms



Programming in C++

Top