Java.lang.Runtime.gc() Method

Advertisements


Description

The java.lang.Runtime.gc() method runs the garbage collector. Calling this method suggests that the Java virtual machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the virtual machine has made its best effort to recycle all discarded objects.

The name gc stands for "garbage collector". The virtual machine performs this recycling process automatically as needed, in a separate thread, even if the gc method is not invoked explicitly. The method System.gc() is the conventional and convenient means of invoking this method.

Declaration

Following is the declaration for java.lang.Runtime.gc() method

public void gc()

Parameters

  • NA

Return Value

This method does not return a value.

Exception

  • NA

Example

The following example shows the usage of lang.Runtime.gc() method.

package com.tutorialspoint;

public class RuntimeDemo {

   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...");
      Runtime.getRuntime().gc();
      System.out.println("Completed.");
   }
}

Let us compile and run the above program, this will produce the following result:

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



Advertisements
Advertisements