Use this code:

// Get current size of heap in bytes.
long heapSize = Runtime.getRuntime().totalMemory();

// Get maximum size of heap in bytes. The heap cannot grow beyond this size.
// Any attempt will result in an OutOfMemoryException.
long heapMaxSize = Runtime.getRuntime().maxMemory();

// Get amount of free memory within the heap in bytes. This size will 
// increase after garbage collection and decrease as new objects are created.
long heapFreeSize = Runtime.getRuntime().freeMemory();

It was useful to me to know it.

Answer from Drewen on Stack Overflow
🌐
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 ...
Discussions

java - Check available heapSize programmatically? - Stack Overflow
I am using Eclipse. The problem is my application crashes if the allocated memory is less then 512MB. Now is there anyway to check the available memory for a program before starting heavy memory More on stackoverflow.com
🌐 stackoverflow.com
How can I find Java heap size and memory used (Linux)? - Stack Overflow
How can I check heap size (and used memory) of a Java application on Linux through the command line? I have tried through jmap. But it gives information about internal memory areas, like Eden, Perm... 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
java - How to check heap usage of a running JVM from the command line? - Stack Overflow
Can I check heap usage of a running JVM from the commandline, I mean the actual usage rather than the max amount allocated with Xmx. I need it to be commandline because I don't have access to a More on stackoverflow.com
🌐 stackoverflow.com
🌐
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 ...
🌐
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 - This method provides a deeper look into heap memory usage beyond just -Xmx. To check the -Xmx value without modifying code, use the following command: java -XX:+PrintFlagsFinal -version | grep MaxHeapSize
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
🌐
Mkyong
mkyong.com › home › java › find out your java heap memory size
Find out your Java heap memory size - Mkyong.com
March 9, 2014 - Java heap size InitialHeapSize = 64781184 bytes (61.7M) and MaxHeapSize = 1038090240 bytes (990M). PermGen Size PermSize = 21757952 bytes (20.75M), MaxPermSize = 174063616 bytes (166M) Thread Stack Size ThreadStackSize = 1024 kilobytes (1M) ...
Find elsewhere
🌐
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
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.
🌐
Coderanch
coderanch.com › t › 620734 › java › identify-default-Java-heapsize-Windows
How to identify default Java heapsize in Windows (Performance forum at Coderanch)
September 26, 2013 - Do you know " java -XX:+PrintFlagsFinal". It prints all possible flags you can pass to the JVM. In addition it also prints the default value for each flag.
🌐
javathinking
javathinking.com › blog › how-can-i-find-java-heap-size-and-memory-used-linux
How to Check Java Heap Size and Used Memory on Linux via Command Line — javathinking.com
Once you have the PID, verify the initial (-Xms) and maximum (-Xmx) heap sizes configured for the JVM. jinfo (Java Configuration Info) retrieves JVM flags for a running process. To check -Xmx (max heap): ... jcmd (Java Command Tool) is a versatile utility for sending commands to a JVM. To list all JVM flags (including -Xms/-Xmx): ... Now, let’s check the actual heap memory being used by the application at runtime.
🌐
Viralpatel
viralpatel.net › getting-jvm-heap-size-used-memory-total-memory-using-java-runtime
Getting Java JVM heap size, used memory, total memory using Java Runtime
May 19, 2009 - /** * Class: TestMemory * @author: ... { int mb = 1024*1024; //Getting the runtime reference from system Runtime runtime = Runtime.getRuntime(); System.out.println("##### Heap utilization statistics [MB] #####"); //Print used ...
🌐
CodingTechRoom
codingtechroom.com › question › -how-to-determine-java-heap-size
How to Determine Java's Heap Size on Your Computer - CodingTechRoom
... // Java program to display current Heap size System.out.println("Maximum Heap Size (bytes): " + Runtime.getRuntime().maxMemory()); System.out.println("Total Heap Size (bytes): " + Runtime.getRuntime().totalMemory()); System.out.println("Free ...
🌐
IBM
ibm.com › support › pages › methods-extracting-java-heap-values-and-monitoring-java-heap-usage-websphere
Methods for Extracting Java Heap Values and Monitoring Java Heap Usage in WebSphere
July 20, 2022 - You can use the Java virtual machine (JVM) counters that the Performance Monitoring Infrastructure (PMI) and Tivoli® Performance Viewer (TPV) collect to monitor JVM performance. The total, used, and free heap size counters are available without any additional configuration settings.
🌐
Datadog
datadoghq.com › blog › java-memory-management
Java Memory Management: How to Monitor | Datadog
November 28, 2025 - The JVM exposes runtime metrics—including information about heap memory usage, thread count, and classes—through MBeans. A monitoring service such as Datadog’s Java Agent can run directly in the JVM, collect these metrics locally, and automatically display them in an out-of-the-box dashboard like the one shown above.
🌐
Vogella
vogella.com › tutorials › JavaPerformance › article.html
Java Performance - Memory and Runtime Analysis - Tutorial
May 31, 2026 - jvisualvm is a tool to analyse the runtime behavior of your Java application. It allows you to trace a running Java program and see its the memory and CPU consumption. You can also use it to create a memory heap dump to analyze the objects in the heap.
🌐
Reddit
reddit.com › r/learnjava › how do you tell how much memory is needed when java can't allocate enough heap space?
r/learnjava on Reddit: How do you tell how much memory is needed when Java can't allocate enough heap space?
June 26, 2018 -

I'm trying to run a server for an old game called MapleStory on a Raspberry Pi. I thought that it would be a good exercise to learn a little bit more about servers, SQL, and Java since the source code is in Java.

The Raspberry Pi only has about 1 GB of RAM. I'm running a lightweight operating system called raspbian stretch Lite. I'm also running a LAMP server. When I go to start the server Java says that it cannot allocate enough heap memory, but I don't know how much more memory it needs. I tried this on my Windows machine originally and it seemed like it would have just enough memory to run the game. I'm not sure how laggy it would be, but I am interested in seeing if I can get it to work by only using the command line interface and a Raspberry Pi. Maybe I can host the server in the cloud, but I'm not sure how much memory is needed. If anyone has any information, it is appreciated. Thanks.

Top answer
1 of 3
2

Show the command line column in task manager, which should have the settings assuming they were passed on the command line:

2 of 3
2

Note that the below answer might require JMX to be enabled - I believe it's disabled by default in public JRE, and requires a restart of the JVM to change it, which would be rather useless in your case. Still, worth a shot?

Whether they work or not will also depend on the specific native wrapping method used by this application.

You should be able to copy these tools along with jli.dll from a JDK with a matching minor version and architecture to the JRE you're running. You could also run the tools remotely, though that's less likely to work without some initial set up due to the security requirements for remote connections.


The jps tool, available in the JDK, should be able to provide this information with the command jps -v. If you have multiple Java processes running, you can identify them by the PID in the first column.

Example output on Netbeans (PID 9056) (which uses a native wrapper similar to your application):

9056  -Dnetbeans.importclass=org.netbeans.upgrade.AutoUpgrade -Dnetbeans.accept_
license_class=org.netbeans.license.AcceptLicense -client -Xss2m -Xms32m -XX:Perm
Size=32m -Dapple.laf.useScreenMenuBar=true -Dapple.awt.graphics.UseQuartz=true -
Dsun.java2d.noddraw=true -Dsun.java2d.dpiaware=true -Dsun.zip.disableMemoryMappi
ng=true -Xmx1024m <snip>

Notice the -Xss, -Xms and -Xmx arguments.


Another thing you can try is jinfo, which allows you to target a specific PID, e.g. jinfo 9056.

NOTE - This utility is unsupported and may or may not be available in future versions of the JDK.


You could also try jconsole and jvisualvm, though they seem to have trouble attaching to wrapped JVMs and listing VM arguments, from my testing.