Open In App

Java Runtime gc() Method with Examples

By recovering space from useless resources, garbage collection in Java streamlines the time-consuming operation of memory management. When memory becomes scarce, the JVM’s garbage collection kicks off immediately. However, developers can utilize the gc() function to actively contact the JVM to perform the work.

Explanation of Concepts

The gc() function is straightforward, with no variations or overloads. It may be accessed using Runtime.getRuntime().gc() or System.gc().



Example of Java Runtime gc() Method

Here are some example codes demonstrating the use of the gc() method:

Example 1:

In this example,, we will discuss Runtime.getRuntime().gc() to request garbage collection.






//Java Program to 
//create garbage collector 
  
public class GFG {
      
      //Main method
    public static void main(String[] args) {
  
      // print when the program starts
      System.out.println("Program starting...");
  
      // run the garbage collector
      System.out.println("Running Garbage Collector...");
        
      // garbage collector instance
      Runtime.getRuntime().gc();
      System.out.println("Completed.");
    }  
}

Output
Program starting...
Running Garbage Collector...
Completed.





Explanation of the above Program:

Example 2: Garbage Collection Before Out of Memory

In this example, we will discuss System.gc() to request garbage collection.




// Java Program to create garbage collector 
// using System.gc()
  
// Driver class
public class GFG {
  
    // Main method
    public static void main(String[] args){
        for (int i = 0; i < 100000; i++) {
            // Create objects in a loop
            new GFG();
        }
  
        // Request garbage collection
        System.gc();
  
        // Message to indicate that the garbage collector
        // was requested
        System.out.println("Garbage collection requested.");
    }
}

Output
Garbage collection requested.





Explanation of the Above Program:

Conclusion

The gc() method in Java allows for a targeted release of memory occupied by unused objects. While Java’s built-in garbage collection is generally effective, it may be necessary to address runtime issues.

When utilized thoughtfully, it can be a valuable asset in your programming toolkit.


Article Tags :