Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Tuesday, July 13, 2021

How to get max memory, free memory and total memory in Java? Example

Getting free memory, total memory and max memory on JVM is using Runtime class in Java. and many java programmers is interested to know whether they have any relationship with JVM argument -Xms and -Xmx which is used to specify starting heap size and maximum heap size of JVM. I have touched this on 10 Points on Java heap and how to set heap size in ANT and Maven but here we will see some way to find out starting and maximum heap size from Java program.

How to find max memory, free memory and total memory in Java

how to find free memory, total memory and max memory in javaAs per Javadoc freeMemory is currently available memory which can be allocated to future objects and totalMemory is the total amount of memory in the Java virtual. Since we know that JVM expands heap whenever it needs so if we start our JVM with -Xms10m and -Xmx120m you should expect that initial freeMemory and totalMemory should be same with starting heap size of JVM as Virtual machine has not been expanded yet and that's the case exactly.

Even value returned by Runtime.maxMemory() will be close to the value of -Xmx though little less. 

In this article, we will see how to get an approximate value of initial and maximum heap size, free memory available in JVM, and used memory or memory currently occupied by objects in heap.

And, if you are serious about improving your advanced JVM skill and learn things like taking and analyzing heap dumps then you can also check these Java performance courses to learn more about Performance and Memory management including troubleshooting memory leaks in Java.

How to get free Memory in Java

In order to get currently free Memory available for creating object use Runtime.getRuntime().freeMemory() method, this will return size in bytes, which you convert in Mega Bytes for better readability. we will see an example of getting initial heap and free memory in code example section. Calling Garbage collector by either System.gc() or Runtime.gc() may results in slightly higher free memory reclaimed by dead objects.

How to get total Memory in Java

You can use Runtime.getRuntime.totalMemory() to get total memory from JVM which represents the current heap size of JVM which is a combination of used memory currently occupied by objects and free memory available for new objects. 

As per Javadoc value returned by totalMemory() may vary over time depending upon the environment. see the code example for getting total memory in Java in the next code example section.

How to get initial Heap Size from Java Program

We specify initial heap space by using -Xms and JVM create an initial heap with this much size. in order to get this size from Java program call Runtime.getRuntime.totalMemory() before creating any object. 

See code example of getting initial heap size from java program in the next section. Apart from –Xms and –Xmx there are a lot of other useful JVM Options I have shared on my post 10 useful JVM parameters Java Programmer should know.

How to get maximum Heap Size from Java Program

This is relatively easy as maximum heap space is not going to change over JVM life cycle and call to Runtime.getRuntime.maxMemory() will return value close to -Xmx but keep in mind exact value will be little less than what have you set.

How to get Used Memory in JVM

by using Runtime.getRuntime.totalMemory() and Runtime.getRuntime.freeMemory() we can calculate how much space has been currently occupied by Java object or you say used memory in JVM as show in below code example of getting memory sizes in Java:

Code Example of getting heap memory in Java program:

In below example, we get the initial size of heap by calling freeMemory, total memory, and max memory at the start of the program and then we create thousands of object which occupy space in heap and not eligible for garbage collection which forces JVM to extend heap. 

Now call to total memory, free memory will return different values based on current heap size but max memory will still return the same. try creating some more object and you will be greeted with java.lang.OutOfMemoryError :)

public class MemoryUtil{

       private static final int MegaBytes = 10241024;

       public static void main(String args[]) {

              long freeMemory = Runtime.getRuntime().freeMemory()/MegaBytes;
              long totalMemory = Runtime.getRuntime().totalMemory()/MegaBytes;
              long maxMemory = Runtime.getRuntime().maxMemory()/MegaBytes;

              System.out.println("JVM freeMemory: " + freeMemory);
              System.out.println("JVM totalMemory also equals to initial heap size of JVM : "
                                         + totalMemory);
              System.out.println("JVM maxMemory also equals to maximum heap size of JVM: "
                                         + maxMemory);

              ArrayList objects = new ArrayList();

              for (int i = 0; i < 10000000; i++) {
                     objects.add(("" + 10 * 2710));

              freeMemory = Runtime.getRuntime().freeMemory() / MegaBytes;
              totalMemory = Runtime.getRuntime().totalMemory() / MegaBytes;
              maxMemory = Runtime.getRuntime().maxMemory() / MegaBytes;

              System.out.println("Used Memory in JVM: " + (maxMemory - freeMemory));
              System.out.println("freeMemory in JVM: " + freeMemory);
              System.out.println("totalMemory in JVM shows current size of java heap : "
                                         + totalMemory);
              System.out.println("maxMemory in JVM: " + maxMemory);


JVM freeMemory: 9
JVM totalMemory also equals to initial heap size of JVM : 9
JVM maxMemory also equals to maximum heap size of JVM: 116
Used Memory in JVM: 81
freeMemory in JVM: 35
totalMemory in JVM shows current size of java heap : 108
maxMemory in JVM: 116

That’s all on how to get free, total, and max memory from JVM using Java programming and Runtime class. This is not the best way to know the sizes and in practice, it will report less size than what have you specified in –Xmx and –Xms but still it's a working solution for most of the needs.

Some other Java Tutorials you may like


Java Memory said...

Good post on how to find memory usage in Java, I was looking for some kind of simple utility to find memory and cpu usage in java program, Can you also let us know how to find cpu usage from Java program, whether its possible or not ?

Anonymous said...

I may be wrong here but shouldn't the MegaBytes variable be 1024 * 1024?

You say in the text that calculating used memory is totalMemory - freeMemory, but in the code example you are using maxMemory instead of totalMemory. The latter would be incorrect. I thought I would just give you a heads up =).

Thanks for the tutorial.

Javin Paul @ sort arraylist in Java said...

@Anonymous, you are absolutely correct. Thanks for pointing that out. MegaBytes is indeed 1024*1024, some how * got disappeared while pasting. Also used memory should be totalMemory- freeMemory. That's a typo. thanks

Blog4U said...

if so many applications are running on JVM then we have to know how much memory is used by our program and how to know how much memory for which object....

Srikanth Kodali said...

Used Memory is always less than the values shows up on Linux top command. Why is this difference?
top command values are not even close to TotalMemory when we give the spike. How do I get the top command values through JAVA program.

Pablo said...

private static final int MegaBytes = 10241024;

should be

private static final int MegaBytes = 1024*1024;

javin paul said...

Thanks Pablo, looks like a formatting issue, will fix it.

Post a Comment