Heap size and memory options
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A Java program's memory limits come from a few JVM options: -Xmx and -Xms for the heap, -Xss for each thread's stack and -XX:MaxMetaspaceSize for class data. When you set none of them, the JVM picks values from the machine it runs on, so the same command can behave differently on a laptop and on a server.
-Xms and -Xmx: starting and maximum heap
The maximum heap, set with -Xmx, is the largest size the Java heap may grow to; -Xms sets the size it starts with. Going beyond -Xmx gives an OutOfMemoryError.
-Xmx sets the maximum size the heap may grow to, and -Xms sets the heap size the JVM starts with. Sizes take a unit: k for KB, m for MB, g for GB, so -Xmx512m means 512 MB. A number with no unit means bytes.
Example 1 · Ask the running program about its heap
public class HeapLimitsDemo { static long toMb(long bytes) { return bytes / (1024 * 1024); }
public static void main(String[] args) { Runtime rt = Runtime.getRuntime(); System.out.println("Max heap (-Xmx): " + toMb(rt.maxMemory()) + " MB"); System.out.println("Committed heap now: " + toMb(rt.totalMemory()) + " MB"); System.out.println("Free inside that: " + toMb(rt.freeMemory()) + " MB"); System.out.println("CPUs the JVM sees: " + rt.availableProcessors()); }}Max heap (-Xmx): 1882 MB Committed heap now: 118 MB Free inside that: 116 MB CPUs the JVM sees: 12
What this code does
Runtime.maxMemory()is the maximum heap,totalMemory()the committed heap andfreeMemory()the free part of it. This run used the defaults on a 7.5 GB machine.- With Serial or Parallel GC,
maxMemory()reports a little less than-Xmx(247 MB for-Xmx256mwith Serial), because one survivor space is not counted. Your numbers will differ.
Example 2 · -Xms and -Xmx in action, and two common mistakes
java -Xms64m -Xmx256m HeapLimitsDemojava -Xms512m -Xmx512m HeapLimitsDemojava -Xmx256 HeapLimitsDemojava -Xms512m -Xmx256m HeapLimitsDemoMax heap (-Xmx): 256 MB Committed heap now: 64 MB Free inside that: 62 MB CPUs the JVM sees: 12 Max heap (-Xmx): 512 MB Committed heap now: 512 MB Free inside that: 509 MB CPUs the JVM sees: 12 Error occurred during initialization of VM Too small maximum heap Error occurred during initialization of VM Initial heap size set to a larger value than the maximum heap size
What this code does
-Xms64m -Xmx256mstarts with 64 MB committed and can grow to 256 MB. With-Xms512m -Xmx512mthe whole heap is committed from the start.-Xmx256has no unit, so it asks for 256 bytes and the JVM refuses to start. A starting size bigger than the maximum is also rejected before your code runs.
The heap the JVM has really taken from the operating system right now is called committed memory. It starts near -Xms and grows towards -Xmx when collections cannot free enough. If the heap is at -Xmx and still full after a collection, the program gets OutOfMemoryError: Java heap space. Many servers set -Xms equal to -Xmx, for example -Xms2g -Xmx2g. The JVM then never spends time growing or shrinking the heap, and you learn at start-up, not at 2 am, whether the machine has that much memory.
Fix the error
Fix the heap options
Read the real error from java, then pick the line that fixes it.
Round 1 of 3
Start with a 512 MB heap that may grow to 256 MB.
Error
Error occurred during initialization of VM Initial heap size set to a larger value than the maximum heap size
The default maximum heap: about a quarter of memory
-XX:MaxRAMPercentage is the share of the machine's memory the JVM uses as the default -Xmx when you do not give one.
Example 3 · Where the default heap comes from
java -XX:+PrintFlagsFinal -version | grep -E "HeapSize|RAMPercentage"openjdk version "21.0.7" 2025-04-15
...
size_t InitialHeapSize = 123731968 {product} {ergonomic}
double InitialRAMPercentage = 1.562500 {product} {default}
...
size_t MaxHeapSize = 1973420032 {product} {ergonomic}
double MaxRAMPercentage = 25.000000 {product} {default}
size_t MinHeapSize = 8388608 {product} {ergonomic}
double MinRAMPercentage = 50.000000 {product} {default}
...What this code does
MaxHeapSize(1973420032 bytes, about 1882 MB) is 25% of this machine's 7.5 GB, and{ergonomic}says the JVM worked it out.InitialHeapSize(about 118 MB) is 1/64 of memory.MaxRAMPercentage = 25andInitialRAMPercentage = 1.5625are the defaults behind those numbers.versionlines go to the screen too, because-versionprints them on the error stream, whichgrepdoes not filter. Lines marked...were trimmed.
On HotSpot (Java 17 and 21) it is 25, so a laptop with 8 GB of RAM gets a default maximum heap of about 2 GB. The default starting heap comes from -XX:InitialRAMPercentage, which is 1.5625, or 1/64 of memory. On very small machines of a few hundred MB, the JVM uses -XX:MinRAMPercentage (50) instead, so a tiny device still gets a usable heap. Defaults change from machine to machine. A college ERP batch job that ran fine on a 16 GB desktop (4 GB heap) can hit OutOfMemoryError on a 4 GB server (1 GB heap) with the same command, so set -Xmx or a percentage on purpose.
-XX:MaxRAMPercentage for containers
A container (such as a Docker container) runs a program with its own memory limit, for example 1 GB, on a bigger machine. On Linux, the JVM reads that limit instead of the host's memory.
Example 4 · MaxRAMPercentage with a 1 GB memory limit
java -XX:MaxRAM=1g -XX:+PrintFlagsFinal -version | grep " MaxHeapSize "java -XX:MaxRAM=1g -XX:MaxRAMPercentage=75 -XX:+PrintFlagsFinal -version | grep " MaxHeapSize "java -XX:MaxRAMPercentage=75 -Xmx512m -XX:+PrintFlagsFinal -version | grep " MaxHeapSize " size_t MaxHeapSize = 268435456 {product} {ergonomic}
size_t MaxHeapSize = 805306368 {product} {ergonomic}
size_t MaxHeapSize = 536870912 {product} {command line}What this code does
-XX:MaxRAM=1gmakes the JVM act as if the machine had 1 GB, like a 1 GB container limit. With the 25% default the heap is 268435456 bytes, only 256 MB.-XX:MaxRAMPercentage=75raises it to 805306368 bytes (768 MB). In the last run-Xmx512mwins over the percentage, and the origin shows{command line}.
This container support is on by default since Java 10 (and in Java 8 from update 191). The 25% default is often too small here: a container usually runs only one JVM, yet a 1 GB limit gives a heap of just 256 MB. Teams therefore set -XX:MaxRAMPercentage=75 or similar. The heap then grows or shrinks with the container limit, and no -Xmx needs to change when the limit changes. Do not use 100%. Thread stacks, class metadata, compiled code and the JVM itself live outside the heap, and if the whole process goes over the limit, the system kills it without any Java error.
-Xmx wins over -XX:MaxRAMPercentage.-Xss and -XX:MaxMetaspaceSize
-Xss sets the stack size of each thread. The stack holds one frame per method call, so deep recursion that runs out of stack ends with StackOverflowError.
java -Xss256k StackDepthDemojava StackDepthDemojava -Xss2m StackDepthDemoThe default is 1 MB on 64-bit Windows and x86 Linux (checked on Windows with Java 21); other platforms may differ.
Every thread gets its own stack, so a bigger -Xss costs memory per thread: 500 threads with -Xss4m can reserve 2 GB. For deep recursion, turning the recursion into a loop is usually a better fix than a bigger stack. -XX:MaxMetaspaceSize caps metaspace, the memory outside the heap that holds class information. By default it has no limit. A cap such as -XX:MaxMetaspaceSize=256m makes a class-loading leak fail early with OutOfMemoryError: Metaspace instead of slowly using up the machine.
Example 5 · How deep can one thread go?
public class StackDepthDemo { static int depth = 0;
static void goDeeper() { depth++; goDeeper(); // no base case: runs until the thread's stack is full }
public static void main(String[] args) { try { goDeeper(); } catch (StackOverflowError e) { System.out.println("StackOverflowError after about " + depth + " calls"); } }}StackOverflowError after about 23618 calls
What this code does
goDeepercalls itself with no base case, so it stops only when the thread's stack is full; the program catches theStackOverflowErrorand prints the count.- With the commands above (Java 21, Windows) it stopped after about 4,000 calls with
-Xss256k, about 22,000 by default and 50,000 to 100,000 with-Xss2m. Counts vary between runs, because methods compiled by the JIT use smaller frames.
Checking real values: PrintFlagsFinal and jcmd VM.flags
-XX:+PrintFlagsFinal prints every JVM flag with the final value the JVM decided on, before your program runs. The last column says where the value came from: {default}, {ergonomic} (worked out by the JVM for this machine) or {command line}.
Example 6 · Checking a running JVM with jcmd
java -Xms256m -Xmx256m ResultsServerDemo # terminal 1: keeps running for 30 sjcmd -l # terminal 2: list running JVMsjcmd ResultsServerDemo VM.flagsjcmd ResultsServerDemo GC.heap_info<pid> ResultsServerDemo <pid> jdk.jcmd/sun.tools.jcmd.JCmd -l ... <pid>: -XX:CICompilerCount=4 -XX:ConcGCThreads=3 -XX:G1ConcRefinementThreads=10 -XX:G1EagerReclaimRemSetThreshold=12 -XX:G1HeapRegionSize=1048576 -XX:G1RemSetArrayOfCardsEntries=12 -XX:G1RemSetHowlMaxNumBuckets=8 -XX:G1RemSetHowlNumBuckets=4 -XX:GCDrainStackTargetSize=64 -XX:InitialHeapSize=268435456 -XX:MarkStackSize=4194304 -XX:MaxHeapSize=268435456 -XX:MaxNewSize=160432128 -XX:MinHeapDeltaBytes=1048576 -XX:MinHeapSize=268435456 -XX:NonNMethodCodeHeapSize=5839372 -XX:NonProfiledCodeHeapSize=122909434 -XX:ProfiledCodeHeapSize=122909434 -XX:ReservedCodeCacheSize=251658240 -XX:+SegmentedCodeCache -XX:SoftMaxHeapSize=268435456 -XX:+UseCompressedOops -XX:+UseG1GC -XX:-UseLargePagesIndividualAllocation <pid>: garbage-first heap total 262144K, used 6651K [0x00000000f0000000, 0x0000000100000000) region size 1024K, 7 young (7168K), 0 survivors (0K) Metaspace used 477K, committed 640K, reserved 1114112K class space used 30K, committed 128K, reserved 1048576K
What this code does
ResultsServerDemois any program that keeps running; Practice 5 writes one.VM.flagsshows-XX:MaxHeapSize=268435456(256 MB) and-XX:+UseG1GC, the values this JVM really uses.GC.heap_infoshows a 262144K (256 MB) G1 heap with 6651K in use and 1024K regions.<pid>stands for the process id, which is different on every run.
For a JVM that is already running, use jcmd, a JDK tool that sends commands to a running Java process. jcmd -l lists the Java processes, and jcmd <pid> VM.flags prints the flags it is really using. You can also give the main class name instead of the process id (<pid>). jcmd <pid> GC.heap_info shows the heap size and how much is in use.
findstr MaxHeapSize where these examples use grep.Next step
Check your understanding
12 quick questions