Java Garbage Collection


Objects are dynamically allocated by the new operator.

 

Java handles de-allocation of unused heap memory automatically, which is called Garbage Collection.

 

The garbage collector main aim is to free heap memory by destroying unreferenced objects.


Advantage

It is more memory efficient because of the garbage collector automatically free heap memory by destroying unreachable objects.


By nulling a reference:

Assign the null value to an object reference.

 Calculate ca=new Calculate();  
ca=null;

By assigning a reference to another:

Calculate ca1=new Calculate();  
Calculate ca2=new Calculate();  
ca1=ca2; 

By anonymous object:

new Calculate();

gc() method

The gc() method is available in system and runtime classes which invoke the garbage collector to perform cleanup processing.

Syntax:

public static void gc(){}  

finalize() method

The finalize() method is invoked just before destroying an object, Garbage Collector calls finalize() method on the object to perform the cleanup process. When the finalize() method completes after that Garbage Collector destroys that object.

Syntax:

protected void finalize()  

Example:

public class GarbageCollection{  
	public void finalize(){
    	System.out.println("Garbage collection");
    }  
	public static void main(String args[]){  
		GarbageCollection g1=new GarbageCollection();  
		GarbageCollection g2=new GarbageCollection();  
		g1=null;  
		g2=g1;  
		System.gc();  
	}  
} 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.