Runtime
Suggest Garbage Collection to the JVM
With this example we are going to demonstrate how to suggest Garbage Collection to the JVM. We are using the Runtime class. Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method. An application cannot create its own instance of this class. In short, to suggest Garbage Collection to the JVM you should:
- Use
getRuntime()
API method of Runtime. This method returns the runtime object associated with the current Java application. - Use
freeMemory()
API method of Runtime. This method returns the amount of free memory in the Java Virtual Machine. - Call
gc()
API method. This method runs the garbage collector. Calling this method suggests that the Java virtual machine expend effort toward recycling unused objects in order to make memory they occupy available for reuse runtime.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; public class SuggestGarbageCollectionToTheJVM { public static void main(String[] args) { // get the runtime object associated with the current Java application Runtime runtime = Runtime.getRuntime(); long freeMemory = runtime.freeMemory(); System.out.println("Free memory in JVM (bytes): " + freeMemory); // Runs the garbage collector. Calling this method suggests that the Java virtual machine expend // effort toward recycling unused objects in order to make memory they occupy available for reuse runtime.gc(); freeMemory = runtime.freeMemory(); System.out.println("Free memory in JVM (bytes): " + freeMemory); } }
Output:
Free memory in JVM (bytes): 4963272
Free memory in JVM (bytes): 5063448
This was an example of how to suggest Garbage Collection to the JVM in Java.