Over a million developers have joined DZone.

Using the Java Runtime API for JVM Memory Details

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

Reading runtime information about Java is useful when your application is struggling to get resources. System Memory is one of the main resources that an application developer has to consider while managing the application. Hence sometimes it is beneficial to see what amount of memory your application using and what amount of free memory is in system.

Java’s Runtime class provides lot of information about the resource details of Java Virtual Machine or JVM. The memory consumed by the JVM can be read by different methods in Runtime class.

The following is a small example of getting/reading JVM Heap Size, Total Memory and used memory using Java Runtime API.

/**
* Class: TestMemory
* @author: Viral Patel
* @description: Prints JVM memory utilization statistics
*/
public class TestMemory {

public static void main(String [] args) {

int mb = 1024*1024;

//Getting the runtime reference from system
Runtime runtime = Runtime.getRuntime();

System.out.println("##### Heap utilization statistics [MB] #####");

//Print used memory
System.out.println("Used Memory:"
+ (runtime.totalMemory() - runtime.freeMemory()) / mb);

//Print free memory
System.out.println("Free Memory:"
+ runtime.freeMemory() / mb);

//Print total available memory
System.out.println("Total Memory:" + runtime.totalMemory() / mb);

//Print Maximum available memory
System.out.println("Max Memory:" + runtime.maxMemory() / mb);
}
}

You may also want to print the memory utilization in Kilobytes KBs. For that just assign 1024 value to the int variable mb.

From http://viralpatel.net/blogs

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}