Invoking Garbage Collection Programmatically – Object Lifetime

10.4 Invoking Garbage Collection Programmatically

Although Java provides facilities to invoke the garbage collector explicitly, there are no guarantees that it will be run. The program can request that garbage collection be performed, but there is no way to force garbage collection to be activated.

The System.gc() method can be used to request garbage collection.

static void gc()

Requests that garbage collection be run.

Alternatively, corresponding methods in the Runtime class can be used. A Java application has a unique Runtime object that can be used by the application to interact with the JVM. An application can obtain this object by calling the method Runtime.getRuntime(). The Runtime class provides several methods related to memory issues:

static Runtime getRuntime()

Returns the Runtime object associated with the current application.

void gc()

Requests that garbage collection be run. There are no guarantees that it will be run. It is recommended to use the more convenient static method System.gc().

long freeMemory()

Returns the amount of free memory (bytes) in the JVM that is available for new objects.

long totalMemory()

Returns the total amount of memory (bytes) available in the JVM, including both memory occupied by current objects and memory available for new objects.

The following points regarding automatic garbage collection should be noted:

  • Trying to initiate garbage collection programmatically does not guarantee that it will actually be run.
  • Garbage collection might not even be run if the program execution does not warrant it. Thus any memory allocated during program execution might remain allocated after program termination, but will eventually be reclaimed by the operating system.
  • There are also no guarantees about the order in which the objects will be garbage collected. Therefore, the program should not make any assumptions based on this criteria.
  • Garbage collection does not guarantee that there will be enough memory for the program to run. A program can rely on the garbage collector to run when memory gets very low, and it can expect an OutOfMemoryError to be thrown if its memory demands cannot be met.

Leave a Reply

Your email address will not be published. Required fields are marked *