Runtime

Get JVM memory information with Runtime

This is an example of how to get the JVM memory information with 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. To get the JVM memory information with Runtime class 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 maxMemory() API method of Runtime. This method returns the maximum amount of memory that the Java virtual machine will attempt to use. If there is no inherent limit then the value Long.MAX_VALUE will be returned.
  • Call totalMemory() API method of Runtime. This method returns the total amount of memory in the Java virtual machine.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

public class GetJVMMemoryInformationWithRuntime {
	
	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);

		long maxMemory = runtime.maxMemory();
		System.out.println("Max memory in JVM (bytes): " + maxMemory);

		long totalMemory = runtime.totalMemory();
		System.out.println("Total memory in JVM (bytes): " + totalMemory);
		
	}

}

Output:

Free memory in JVM (bytes): 4963280
Max memory in JVM (bytes): 66650112
Total memory in JVM (bytes): 5177344

 
This was an example of how to get the JVM memory information with Runtime class in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He 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
Inline Feedbacks
View all comments
Back to top button