What does System.gc() and Runtime.gc() methods do?

Solution:

These methods can be used as a hint to the JVM, in order to start a garbage collection. However, this it is up to the Java Virtual Machine (JVM) to start the garbage collection immediately or later in time.

Sample class ReferenceObject is shown below to demonstrate the usage of System.gc and Runtime.gc methods.

public class ReferenceObject
{  
 public void finalize()
 {
    System.out.println("object is garbage collected");
   
 }
 
 public static void main(String args[]){  
  ReferenceObject refObj1=new ReferenceObject();  
  ReferenceObject refObj2=new ReferenceObject();  
  refObj1=null;  
  refObj2=null;  
  System.gc(); 
 
  Runtime.gc(); 
 }  
}
0 answers