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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button