You could use JMX to collect the usage of heap memory at runtime.


Code Example:

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryType;
import java.lang.management.MemoryUsage;

for (MemoryPoolMXBean mpBean: ManagementFactory.getMemoryPoolMXBeans()) {
    if (mpBean.getType() == MemoryType.HEAP) {
        System.out.printf(
            "Name: %s: %s\n",
            mpBean.getName(), mpBean.getUsage()
        );
    }
}

Output Example:

Name: Eden Space: init = 6619136(6464K) used = 3754304(3666K) committed = 6619136(6464K) max = 186253312(181888K)
Name: Survivor Space: init = 786432(768K) used = 0(0K) committed = 786432(768K) max = 23265280(22720K)
Name: Tenured Gen: init = 16449536(16064K) used = 0(0K) committed = 16449536(16064K) max = 465567744(454656K)

If your have question about "Eden Space" or "Survivor Space", check out How is the java memory pool divided

Answer from Mike Lue on Stack Overflow
Top answer
1 of 3
22

You could use JMX to collect the usage of heap memory at runtime.


Code Example:

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryType;
import java.lang.management.MemoryUsage;

for (MemoryPoolMXBean mpBean: ManagementFactory.getMemoryPoolMXBeans()) {
    if (mpBean.getType() == MemoryType.HEAP) {
        System.out.printf(
            "Name: %s: %s\n",
            mpBean.getName(), mpBean.getUsage()
        );
    }
}

Output Example:

Name: Eden Space: init = 6619136(6464K) used = 3754304(3666K) committed = 6619136(6464K) max = 186253312(181888K)
Name: Survivor Space: init = 786432(768K) used = 0(0K) committed = 786432(768K) max = 23265280(22720K)
Name: Tenured Gen: init = 16449536(16064K) used = 0(0K) committed = 16449536(16064K) max = 465567744(454656K)

If your have question about "Eden Space" or "Survivor Space", check out How is the java memory pool divided

2 of 3
4

maybe an useful update using Java 17 to 19: After several trials with getRuntime() and old/Eden/Survivor Space I came back to use getRuntime() which seem to be 'faithful' now:

With Java 17-19 therefore I propose to use the heap size functions of getRuntime():

Runtime env = Runtime.getRuntime();

System.out.println("Max Heap Size = maxMemory() = " + env.maxMemory()); //max heap size from -Xmx, i.e. is constant during runtime
System.out.println("Current Heap Size = totalMemory() = " +  env.totalMemory()); //currently assigned  heap
System.out.println("Available in Current Heap = freeMemory() = " + env.freeMemory()); //current heap will extend if no more freeMemory to a maximum of maxMemory
System.out.println("Currently Used Heap = " + (env.totalMemory()-env.freeMemory()) );
System.out.println("Unassigned Heap = " + (env.maxMemory()-env.totalMemory()));
System.out.println("Currently Totally Available Heap Space = "+ ((env.maxMemory()-env.totalMemory()) + env.freeMemory()) ); //available=unassigned + free
🌐
Baeldung
baeldung.com › home › java › jvm › java heap space memory with the runtime api
Java Heap Space Memory with the Runtime API | Baeldung
January 8, 2024 - The Runtime#getTotalMemory method returns the total heap space currently reserved by the JVM in bytes. It includes the memory reserved for current and future objects. Hence, it isn’t guaranteed to be constant during the program execution since ...
Discussions

java - How to view the current heap size that an application is using? - Stack Overflow
I think I increased my heap size to 1 GB in NetBeans since I changed the config to look like this: netbeans_default_options="-J-Xmx1g ...... After I restarted NetBeans, can I be sure that my app is More on stackoverflow.com
🌐 stackoverflow.com
java - Read maximum heap space at runtime - Stack Overflow
As we all know, the java -Xmx option is used to set the maximum heap space available to a Java program. But is there a way for a Java program to read the value that has been set? Something like Sys... More on stackoverflow.com
🌐 stackoverflow.com
How can I find Java heap size and memory used (Linux)? - Stack Overflow
How to find the memory usage separated ... specific java process by pid ? 2017-01-17T07:04:45.323Z+00:00 ... @GaryGauh This is the default heap size. To find usage of running application you should do it within code or you can use jconsole. This is what I know there should also be many other ways. 2017-01-18T06:47:22.023Z+00:00 ... Use jstat -gc for running applications. 2018-07-03T09:53:57.457Z+00:00 ... You can't get dynamic ... More on stackoverflow.com
🌐 stackoverflow.com
Command Line Tool for monitoring Java Heap - Unix & Linux Stack Exchange
Is there any command line tool for monitoring the heap size usage of Java in CentOS? More on unix.stackexchange.com
🌐 unix.stackexchange.com
🌐
Baeldung
baeldung.com › home › java › jvm › command-line tools to find the java heap size
Command-Line Tools to Find the Java Heap Size | Baeldung
January 27, 2024 - For instance, we can use jstat -gc to see heap statistics: $ jstat -gc 4309 S0C S1C S0U S1U EC EU OC OU MC 0.0 0.0 0.0 0.0 129024.0 5120.0 75776.0 10134.6 20864.0 MU CCSC CCSU YGC YGCT FGC FGCT CGC CGCT GCTGCT 19946.2 2688.0 2355.0 2 0.007 1 ...
🌐
Mkyong
mkyong.com › home › java › find out your java heap memory size
Find out your Java heap memory size - Mkyong.com
March 9, 2014 - Heap sizes Initial heap size of 1/64 of physical memory up to 1Gbyte Maximum heap size of 1/4 of physical memory up to 1Gbyte · However, above algorithms are just for reference, it may vary in different VM. ... 1. Java Heap Size Place to store objects created by your Java application, this is where Garbage Collection takes place, the memory used by your Java application.
🌐
Blogger
javarevisited.blogspot.com › 2012 › 01 › find-max-free-total-memory-in-java.html
How to get max memory, free memory and total memory in Java? Example
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 :)
🌐
Planet of Bits
planetofbits.com › home › how to find heap size in java
How to find Heap size in Java - Planet of Bits
August 27, 2014 - java.lang.Runtime class has the following 3 methods which can give information about the heap memory size: totalMemory() – Returns the total amount of memory in the Java virtual machine. maxMemory() – Returns the maximum amount of memory ...
Find elsewhere
🌐
Blogger
javarevisited.blogspot.com › 2011 › 05 › java-heap-space-memory-size-jvm.html
10 points about Java Heap Space or Java Heap Memory
5. You can use either JConsole or Runtime.maxMemory(), Runtime.totalMemory(), Runtime.freeMemory() to query about Heap size programmatic in Java. See my post How to find memory usage in Java program for more details.
🌐
Mohibul Hassan
mohibulsblog.netlify.app › posts › day 60: generating jvm heap dump programmatically
Day 60: Generating JVM heap dump programmatically | Mohibul Hassan
March 31, 2026 - Generating Heap dumps programatically by using MBeanServer and PlatformBeans to get Management information from JVM
🌐
Index.dev
index.dev › blog › check-xmx-value-java-runtime
Java Xmx: Check Max Heap Size at Runtime | -Xmx Command & Examples | Index.dev
February 14, 2025 - The -Xmx JVM option sets the maximum heap size for your Java application. It controls how much memory the JVM can allocate before throwing an OutOfMemoryError. Checking your Xmx value at runtime is essential for diagnosing memory issues, optimizing ...
🌐
Wordpress
vk4u.wordpress.com › 2016 › 08 › 02 › find-java-heap-memory-size
Find Java heap memory size. |
August 2, 2016 - To Find out java memory,execute java -XX:+PrintFlagsFinal -version | grep -aiE “HeapSize|permsize|threadstacksize” [root@vpm ~]# java -XX:+PrintFlagsFinal -version | grep -aiE “He…
🌐
javaspring
javaspring.net › blog › set-java-heap-space
Understanding and Setting Java Heap Space — javaspring.net
However, you cannot directly set the heap size programmatically. You can get the current heap size using the following code:
Top answer
1 of 2
4

What's wrong with MXBeans? The implementation is not so hard.

I've used something like that :

    List<GarbageCollectorMXBean> gcList = ManagementFactory.getGarbageCollectorMXBeans();
    for(GarbageCollectorMXBean tmpGC : gcList){

        System.out.println("\nName: " + tmpGC.getName());
        System.out.println("Collection count: " + tmpGC.getCollectionCount());
        System.out.println("Collection time: " + tmpGC.getCollectionTime());
        System.out.println("Memory Pools: ");

        String[] memoryPoolNames = tmpGC.getMemoryPoolNames();
        for(String mpnTmp : memoryPoolNames){
            System.out.println("\t" + mpnTmp);
        }

    }

    System.out.println( "Memory Pools Info" );
    List<MemoryPoolMXBean> memoryList = ManagementFactory.getMemoryPoolMXBeans();
    for(MemoryPoolMXBean tmpMem : memoryList){

        System.out.println("\nName: " + tmpMem.getName());
        System.out.println("Usage: " + tmpMem.getUsage());
        System.out.println("Collection Usage: " + tmpMem.getCollectionUsage());
        System.out.println("Peak Usage: " + tmpMem.getPeakUsage());
        System.out.println("Type: " + tmpMem.getType());
        System.out.println("Memory Manager Names: ") ;

        String[] memManagerNames = tmpMem.getMemoryManagerNames();
        for(String mmnTmp : memManagerNames){
            System.out.println("\t" + mmnTmp);
        }
        System.out.println("\n");
    }

    MemoryUsage mu =ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
    MemoryUsage muNH =ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
    System.out.println(
            "Init :"+mu.getInit()+
            "\nMax :"+mu.getMax()+
            "\nUsed :"+mu.getUsed()+
            "\nCommited :"+mu.getCommitted()+
            "\nInit NH :"+muNH.getInit()+
            "\nMax NH :"+muNH.getMax()+
            "\nUsed NH:"+muNH.getUsed()+
            "\nCommited NH:"+muNH.getCommitted());
2 of 2
2

You can launch the JVM with options to control runtime output of this kind of information.

See the java tool documentation.

For example to ouput to the console:

java -verbose:gc

or to output to file:

java -Xloggc:your.log.file

With either of these options, the JVM logs every GC event while the VM is running (not just when it exits).