The process of releasing the heap memory occupied by objects which do not have any live references in the Java program is known as garbage collection.
Whenever a Java program is compiled and executed, JVM creates three threads
Main thread - this thread is responsible for running the main method()
in the Java program
Thread Scheduler - this thread controls the scheduling of the threads in the program like which thread should execute first or which thread should execute after which thread etc.
Garbage Collector Thread - this thread is responsible to release the garbage blocks present in the memory and is the main focus of this article
Garbage Collector thread works in the background, performs its tasks in background and comes in the category of daemon threads or low priority threads
finalize()
, to make sure that the objects have completed their processes or notfinalize()
method can be considered to have almost the same functionality as destructors()
in C++finalize()
method is executed, the garbage collector releases the memory of the objects and hence protects the program from unwanted memory leaksSchool obj = new School();
obj = null;
Here the obj
variable, first refers to an object in the heap memory but after nulling the obj
there is no other reference to that object, hence garbage collector identifies it and releases that object’s memory.
School obj1 = new School();
School obj2 = new School();
obj1 = obj2;
Now the object previously referenced by obj1
in the heap memory is available for garbage collection as no live reference is available for that object now.
new School();
Anonymous objects don’t have any reference so garbage collector releases their memory once they serve their purpose
File : Test.java
import java.io.*;
public class Test{
public void finalize()
{
System.out.println("Memory is freed");
}
public static void main(String args[]){
Test obj1=new Test();
Test obj2=new Test();
obj1=null;
obj2=null;
System.gc();
}
}
Output
$ javac Test.java
$ java Test
Memory is freed
Memory is freed
obj1
and obj2
are dereferenced by assinging null
, after which the objects don’t have any live reference in the program and are now available for garbage collectiongc()
method requests to invoke the garbage collectorfinalize()
method for both objectsfinalize()
method it frees up the memoryHelp us improve this content by editing this page on GitHub