Skip to Content

Suggest JVM to Run Garbage Collector Example

  1. /*
  2.         Suggest JVM to Run Garbage Collector Example
  3.         This Java example shows how to suggest the JVM to run garbage
  4.         collection using gc method of Runtime class.
  5.        
  6. */
  7. public class RunGarbageCollector {
  8.  
  9.         public static void main(String args[])
  10.         {
  11.                 /*
  12.                  * get current Java Runtime using getRuntime()
  13.                  * method of Runtime class.
  14.                  */
  15.                 Runtime runtime = Runtime.getRuntime();
  16.                
  17.                 /*
  18.                  * To suggest the JVM to run garbage collector, use
  19.                  *
  20.                  * void gc()
  21.                  * method of Runtime class.
  22.                  *
  23.                  */
  24.                  
  25.                  runtime.gc();
  26.                  System.out.println("JVM has made best effort to garbage collect!");
  27.         }
  28.        
  29. }
  30.  
  31. /*
  32. Output of this program would be
  33. JVM has made best effort to garbage collect!
  34. */