Garbage Collection in Java

Previous
Next

Garbage Collection:

  • We create objects in memory (Heap area).
  • Every object has a reference variable.
  • Garbage collection is a mechanism of deleting objects which are no longer use in the application.
  • Object is eligible for Garbage collection when it is un-referenced.
class Test 
{
	public static void main(String[] args) 
	{
		Test  obj = new Test();  // referenced object
		new Test(); // un-referenced object
	}
}

Process of GC:

  • When object become unreferenced, JVM invokes finalize() method on that object.
  • finalize() method is pre-defined in java.lang.Object class
  • finalize() method is protected type.
  • finalize() method is used to define closing statements of resource before object deletion.
  • We must override finalize() method into Child class.
class Object
{
	protected void finalize() throws Throwable
	{
	     Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. 
	     A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.
	}
}
Previous
Next

Add Comment

Courses Enquiry Form