1.

How can you make a request for garbage collection in Java?

Answer»

There are two ways to ask the JVM to run the Garbage Collection.

  • The garbage collection methods are available in the Runtime CLASS given by Java. For any Java program code, the Runtime class is a singleton. A singleton instance of the Runtime class is returned by the function getRuntime(). This instance of Runtime can be used to call the gc() function to request garbage collection.
  • Request the JVM to PERFORM GC USING the System class System.gc() function.
 public class Sample{ public static void main(String[] args) throws InterruptedException { Sample s1 = new Sample(); Sample s2 = new Sample(); // Making the reference VARIABLE as null s1 = null; // Calling the system call function for garbage collection System.gc(); // Making the reference variable as null s2 = null; // Calling for garbage collection through the getRuntime() method Runtime.getRuntime().gc(); } @Override // This method is called on object once before garbage collecting it protected void finalize() throws Throwable { System.out.println("Garbage COLLECTOR has been called"); System.out.println("The Object whose garbage has been collected is : " + this); }}

Output:

Garbage collector has been calledThe Object whose garbage has been collected is : Sample@4251f172Garbage collector has been calledThe Object whose garbage has been collected is : Sample@481e8172

Explanation:

In the above code, we create two instances of a class and then re-initialize it to null. Then we call for the garbage collection using the two methods specified above. Thus, we get the above output.



Discussion

No Comment Found