Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Java Garbage Collection

In java, garbage means unreferenced objects. The unused memory automatically collected by which process is known as Garbage Collection. That means it is a process to destroy the unused memory. In JAVA it is performing automatically. So in JAVA memory management is better

Advantage of Garbage Collection

  1. It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
  2. It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.

How can an object be unreferenced?

There are many ways:

  1. By nulling the reference
  2. By assigning a reference to another
  3. By annonymous object etc.
1) By nulling a reference:

Customer c=new Customer();

2) By assigning a reference to another:

Customer c1=newCustomer();
Customer c2=new Customer();
c1=c2;//now the first object referred by c1 is available for garbage collection

3) By annonymous object:

new Customer();

finalize() method

when finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as:
protected void finalize(){}

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

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.
public static void gc(){}

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

public class GarbageDemo{  
	public void finalize()
		System.out.println("Silan Software");
	 public  static  void main(String[]args)
		GarbageDemoob1= new GarbageDemo();
		GarbageDemoob2= new GarbageDemo();
		ob1= null ;
		ob2= null ;

object is garbage collected
object is garbage collected

Note: Neither finalization nor garbage collection is guaranteed.

About the Author

Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc