Java JVM Options
Java JVM options are command-line flags that control how the Java Virtual Machine runs your program: how much memory it may use, which garbage collector cleans that memory, what happens when memory runs out, and which settings your code can read. You pass them to the java command before the class or JAR name. The right JVM options make an application predictable in production; the wrong ones cause slow pauses or crashes.
This lesson explains the JVM options you will actually use, shows how to check which values are in effect, and ends with a production options file for the CourseServer app from Java Production Setup. All examples were run on JDK 21 on a Linux machine with 6 GB of RAM and 2 CPUs.
Java JVM Options Syntax: Standard, -X and -XX Flags
Every option goes before the main class or -jar. Anything after it is passed to your main(String[] args) instead.
java [JVM options] MainClass [program arguments]
java [JVM options] -jar app.jar [program arguments]
| Prefix | Type | Example | Stability |
|---|---|---|---|
- | Standard option | -cp, -jar, -version, -D | Same on every JVM |
-X | Extra option | -Xmx512m, -Xss1m, -Xlog:gc | Stable in HotSpot (OpenJDK) |
-XX:+Name | Turn a boolean flag on | -XX:+UseG1GC | HotSpot advanced flag |
-XX:-Name | Turn a boolean flag off | -XX:-UseCompressedOops | HotSpot advanced flag |
-XX:Name=value | Set a value | -XX:MaxRAMPercentage=75 | HotSpot advanced flag |
-Dname=value | System property for your code | -Dapp.env=prod | Read with System.getProperty |
Sizes accept the suffixes k, m and g (case-insensitive): -Xmx512m, -Xmx2g, -Xss256k.
# correct: options before the class
java -Xmx512m MemoryInfo
# wrong: -Xmx512m becomes args[0] and the JVM ignores it
java MemoryInfo -Xmx512m
How it works:
- The launcher reads options from left to right until it reaches the main class or
-jar app.jar. Everything after that belongs to your program. - When the same option appears twice, the last one wins.
java -Xmx256m -Xmx1g Appruns with a 1 GB heap.
Set Java Heap Size With -Xms and -Xmx
The heap is the memory where your objects live. Two options control it:
| Option | Meaning | Default |
|---|---|---|
-Xms<size> | Initial heap size, reserved at startup | 1/64 of physical RAM |
-Xmx<size> | Maximum heap size, the hard limit | 1/4 of physical RAM |
This program prints the memory the JVM thinks it has:
public class MemoryInfo {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
long mb = 1024 * 1024;
System.out.println("Processors : " + runtime.availableProcessors());
System.out.println("Max heap : " + runtime.maxMemory() / mb + " MB");
System.out.println("Total heap : " + runtime.totalMemory() / mb + " MB");
System.out.println("Free heap : " + runtime.freeMemory() / mb + " MB");
}
}
javac MemoryInfo.java
java MemoryInfo
java -Xms256m -Xmx512m MemoryInfo
Processors : 2
Max heap : 1496 MB
Total heap : 96 MB
Free heap : 94 MB
Processors : 2
Max heap : 512 MB
Total heap : 258 MB
Free heap : 255 MB
How it works:
- Without options, the JVM picks a maximum of about 25% of RAM (1.5 GB of 6 GB here) and starts small (96 MB). It grows the heap only when needed.
maxMemory()reports-Xmx.totalMemory()is what is currently reserved, which starts at about-Xms.freeMemory()is the unused part of the reserved heap, not of the whole machine.
Note: The heap is not the only memory Java uses. Thread stacks, loaded classes (metaspace), the JIT compiler and direct buffers live outside it. A JVM with
-Xmx512mtypically uses 650–800 MB of RAM in total, so leave room for that.
Size the Heap as a Percentage of RAM
In containers and on servers of different sizes, a percentage is easier to maintain than a fixed number.
java -XX:MaxRAMPercentage=50 MemoryInfo
Processors : 2
Max heap : 2990 MB
Total heap : 96 MB
Free heap : 94 MB
| Option | Meaning |
|---|---|
-XX:MaxRAMPercentage=75 | Max heap = 75% of available RAM (or the container memory limit) |
-XX:InitialRAMPercentage=50 | Initial heap = 50% of available RAM |
How it works:
- The JVM detects the container memory limit, so in Docker
--memory=1gwith-XX:MaxRAMPercentage=75gives a 768 MB heap, as used in Dockerize a Java Application. -Xmxoverrides the percentage options if both are given. Pick one style per application.
Check JVM Option Values With PrintFlagsFinal
Never guess which value a flag has. Two built-in options show it.
java -XshowSettings:vm -version
VM settings:
Max. Heap Size (Estimated): 1.46G
Using VM: OpenJDK 64-Bit Server VM
-XX:+PrintFlagsFinal prints every flag (more than 500) with its final value. Filter it with grep:
java -Xmx512m -XX:+PrintFlagsFinal -version | grep -E ' (MaxHeapSize|InitialHeapSize|UseG1GC|UseSerialGC|UseZGC|ThreadStackSize|MaxRAMPercentage) '
size_t InitialHeapSize = 98566144 {product} {ergonomic}
size_t MaxHeapSize = 536870912 {product} {command line}
double MaxRAMPercentage = 25.000000 {product} {default}
intx ThreadStackSize = 1024 {pd product} {default}
bool UseG1GC = true {product} {ergonomic}
bool UseSerialGC = false {product} {default}
bool UseZGC = false {product} {default}
How it works:
- The last column says where each value came from:
{command line}(you set it),{ergonomic}(the JVM chose it based on the machine) or{default}. MaxHeapSize = 536870912bytes is exactly 512 MB, confirming that-Xmx512mwas applied.-versionmakes the JVM print the flags and exit without running a program.
Choose a Garbage Collector
The garbage collector (GC) frees memory used by objects that are no longer reachable. HotSpot ships several, each with a different trade-off.
| Option | Collector | Best for | Pause times |
|---|---|---|---|
-XX:+UseSerialGC | Serial | Tiny apps, 1 CPU, small heaps | Longest, stops everything |
-XX:+UseParallelGC | Parallel | Batch jobs where throughput matters most | Long, but rare |
-XX:+UseG1GC | G1 (default) | Most server applications | Short, target 200 ms |
-XX:+UseZGC | ZGC | Large heaps, low-latency APIs | Under 1 ms |
This program creates a lot of short-lived garbage:
import java.util.ArrayList;
import java.util.List;
public class GcDemo {
public static void main(String[] args) {
List<String> batch = new ArrayList<>();
for (int i = 0; i < 3_000_000; i++) {
batch.add("order-" + i); // short-lived garbage
if (batch.size() == 100_000) batch.clear();
}
System.out.println("Done");
}
}
java -Xmx128m -Xlog:gc GcDemo
java -Xmx128m -XX:+UseZGC -Xlog:gc GcDemo
[0.003s][info][gc] Using G1
[0.051s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 7M->5M(96M) 4.133ms
[0.060s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 8M->7M(96M) 1.827ms
[0.069s][info][gc] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 15M->10M(96M) 3.326ms
[0.105s][info][gc] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 64M->13M(96M) 3.078ms
...
Done
[0.011s][info][gc] Using The Z Garbage Collector
[0.263s][info][gc] GC(0) Garbage Collection (Warmup) 122M(95%)->12M(9%)
Done
How it works:
-Xlog:gcprints one line per collection.64M->13M(96M) 3.078msmeans the heap held 64 MB before the collection, 13 MB after, out of 96 MB reserved, and the pause took about 3 ms.- G1 is chosen automatically on server-class machines (2+ CPUs and 2+ GB RAM). On a 1-CPU container the JVM may pick Serial instead, so set
-XX:+UseG1GCexplicitly in production. - ZGC does most of its work while your threads keep running, so it reports cycles rather than long pauses. In JDK 21+ add
-XX:+ZGenerationalfor the generational version; from JDK 23 it is the default ZGC mode.
Note: Start with G1 and change only when GC logs show a real problem. Switching collectors without measurements rarely helps.
Write GC Logs to a File
In production, GC logs go to a rotating file so you can investigate slowdowns after they happen.
-Xlog:<what>:<where>:<decorations>:<output options>
java -Xmx128m \
-Xlog:gc*:file=logs/gc.log:time,uptime,level,tags:filecount=5,filesize=10m \
GcDemo
head -n 3 logs/gc.log
Done
[2026-11-18T05:18:13.819+0000][0.004s][info][gc,init] CardTable entry size: 512
[2026-11-18T05:18:13.819+0000][0.004s][info][gc ] Using G1
[2026-11-18T05:18:13.820+0000][0.006s][info][gc,init] Version: 21.0.12.1+1-1-24.04.4-Ubuntu (release)
| Part | Value here | Meaning |
|---|---|---|
| What | gc* | All GC-related tags (gc, gc,heap, gc,phases, ...) |
| Where | file=logs/gc.log | Output file (stdout and stderr also work) |
| Decorations | time,uptime,level,tags | Wall-clock time, JVM uptime, level, tags on each line |
| Output options | filecount=5,filesize=10m | Keep 5 files of 10 MB each, then rotate |
How it works:
gc*logs far more detail thangc, including the heap layout at startup and the time of each GC phase.- Rotation caps disk usage at 50 MB. The JVM renames
gc.logtogc.log.0,gc.log.1and so on. - The
logsfolder must exist before the JVM starts, or logging to the file fails with a warning.
Handle OutOfMemoryError Safely
When the heap is full and the GC cannot free enough space, the JVM throws java.lang.OutOfMemoryError. This program leaks memory on purpose:
import java.util.ArrayList;
import java.util.List;
public class LeakyCache {
public static void main(String[] args) {
List<byte[]> cache = new ArrayList<>();
for (int i = 1; ; i++) {
cache.add(new byte[1024 * 1024]); // 1 MB per entry, never removed
if (i % 20 == 0) System.out.println("Cached " + i + " MB");
}
}
}
java -Xmx64m LeakyCache
Cached 20 MB
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at LeakyCache.main(LeakyCache.java:8)
In a web server, only the thread that hit the error dies. The process keeps running in a broken state. Three options fix that:
mkdir -p dumps
java -Xmx64m \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=dumps \
-XX:+ExitOnOutOfMemoryError \
LeakyCache
echo "exit code: $?"
ls dumps
Cached 20 MB
java.lang.OutOfMemoryError: Java heap space
Dumping heap to dumps/java_pid403.hprof ...
Heap dump file created [36118832 bytes in 0.023 secs]
Terminating due to java.lang.OutOfMemoryError: Java heap space
exit code: 3
java_pid403.hprof
| Option | Effect |
|---|---|
-XX:+HeapDumpOnOutOfMemoryError | Writes a snapshot of every object in the heap |
-XX:HeapDumpPath=dumps | Folder (or file name) for the dump |
-XX:+ExitOnOutOfMemoryError | Exits the JVM right after the first OOM |
-XX:+CrashOnOutOfMemoryError | Like Exit, but also writes a crash log (hs_err_pid*.log) |
How it works:
- The
.hproffile can be opened in Eclipse MAT or VisualVM to see which objects filled the heap. Here it would show oneArrayListholding thousands ofbyte[]. - Exit code
3tells systemd or Docker that the process failed, soRestart=on-failurestarts a fresh JVM within seconds. - Each byte array here is 1 MB, so G1 stores it as a "humongous" object in its own region. That is why the 64 MB heap fills after only about 20–30 entries.
Note: A heap dump is as large as the used heap and may contain passwords and personal data from memory. Put dumps on a disk with enough space and restrict who can read them.
Set the Thread Stack Size With -Xss
Each thread has its own stack for method calls and local variables. -Xss sets its size. Deep recursion fills it and throws StackOverflowError.
public class Recursion {
static int depth = 0;
static void dive() {
depth++;
dive();
}
public static void main(String[] args) {
try {
dive();
} catch (StackOverflowError e) {
System.out.println("Stack overflow at depth " + depth);
}
}
}
java Recursion
java -Xss256k Recursion
java -Xss4m Recursion
Stack overflow at depth 23306
Stack overflow at depth 3644
Stack overflow at depth 101948
How it works:
- The default stack on 64-bit Linux is 1 MB (
ThreadStackSize = 1024in KB, from the earlierPrintFlagsFinaloutput). - A bigger stack allows deeper recursion, and a smaller one saves memory when you run thousands of platform threads. 1,000 threads × 1 MB = 1 GB of reserved stack space.
- The exact depth changes from run to run because the JIT compiler changes how much stack each call needs.
Pass Settings to Your Code With -D System Properties
-Dname=value creates a system property that your code reads at runtime. It is the JVM-native way to pass configuration.
public class AppSettings {
public static void main(String[] args) {
String env = System.getProperty("app.env", "dev");
int port = Integer.getInteger("app.port", 8080);
boolean debug = Boolean.getBoolean("app.debug");
System.out.println("env=" + env + ", port=" + port + ", debug=" + debug);
System.out.println("timezone=" + java.util.TimeZone.getDefault().getID()
+ ", encoding=" + System.getProperty("file.encoding"));
}
}
java AppSettings
java -Dapp.env=prod -Dapp.port=9090 -Dapp.debug=true -Duser.timezone=Asia/Kolkata AppSettings
env=dev, port=8080, debug=false
timezone=Asia/Calcutta, encoding=UTF-8
env=prod, port=9090, debug=true
timezone=Asia/Kolkata, encoding=UTF-8
| Method | Reads | Returns when missing |
|---|---|---|
System.getProperty("k", "def") | Any property as String | The default |
Integer.getInteger("k", 8080) | A property parsed as int | The default |
Boolean.getBoolean("k") | true only if the value is "true" | false |
How it works:
- Without
-D, the program uses its defaults. With-D, the same compiled class behaves differently, so one build serves every environment. - Some properties change JDK behavior directly.
-Duser.timezonesets the default time zone (the first run shows the machine's own zone), and-Dfile.encodingsets the default charset (UTF-8 by default since JDK 18). Boolean.getBooleanreads a system property, not a string. It is a common source of confusion withBoolean.parseBoolean.
Keep JVM Options in an Argument File
Long command lines are hard to read and easy to break. An argument file holds one or more options per line, and you pass it with @.
# jvm.options
-Xms256m
-Xmx256m
-XX:+UseG1GC
-XX:+ExitOnOutOfMemoryError
-Dapp.env=prod
This program prints the options the JVM actually received:
import java.lang.management.ManagementFactory;
public class ShowJvmArgs {
public static void main(String[] args) {
System.out.println("JVM arguments:");
for (String arg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
System.out.println(" " + arg);
}
String gcNames = ManagementFactory.getGarbageCollectorMXBeans().stream()
.map(gc -> gc.getName()).toList().toString();
System.out.println("Collectors: " + gcNames);
System.out.println("Max heap: " + Runtime.getRuntime().maxMemory() / (1024 * 1024) + " MB");
}
}
java @jvm.options ShowJvmArgs
JVM arguments:
-Xms256m
-Xmx256m
-XX:+UseG1GC
-XX:+ExitOnOutOfMemoryError
-Dapp.env=prod
Collectors: [G1 Young Generation, G1 Concurrent GC, G1 Old Generation]
Max heap: 256 MB
How it works:
- Lines starting with
#are comments. Each option is read as if it were typed on the command line. getInputArguments()returns the JVM options (not your program arguments). Logging it at startup records exactly how each server was configured.- The collector names confirm G1 is active, which is useful when the JVM could have chosen a different one on a small machine.
Set JVM Options With Environment Variables
When you cannot change the command (for example, a script or image you do not own), use an environment variable.
JDK_JAVA_OPTIONS="-Xmx300m" java ShowJvmArgs
NOTE: Picked up JDK_JAVA_OPTIONS: -Xmx300m
JVM arguments:
-Xmx300m
Collectors: [G1 Young Generation, G1 Concurrent GC, G1 Old Generation]
Max heap: 300 MB
| Variable | Read by | Typical use |
|---|---|---|
JDK_JAVA_OPTIONS | Only the java launcher (JDK 9+) | Add options to every java command |
JAVA_TOOL_OPTIONS | Every JVM, including javac, jshell and agents | Corporate proxies, trust stores, agents |
JAVA_OPTS | Nothing in the JDK itself | A convention used by scripts such as Tomcat's catalina.sh |
How it works:
- The JVM prints a
NOTEorPicked up ...line so you can see that hidden options were applied. - Options in
JDK_JAVA_OPTIONScome before the command-line options, so the command line still wins if both set the same flag.
Real-World Example: Production JVM Options for CourseServer
This options file is the one referenced by the systemd unit in Java Production Setup. It is tuned for a 2 CPU, 2 GB server running a single web application.
# /etc/courseserver/jvm.options — CourseServer, 2 GB VM, JDK 21
# --- memory: fixed 1 GB heap, leaves ~1 GB for metaspace, threads, OS ---
-Xms1g
-Xmx1g
-XX:MaxMetaspaceSize=256m
-Xss512k
# --- garbage collector: G1, aim for pauses under 100 ms ---
-XX:+UseG1GC
-XX:MaxGCPauseMillis=100
# --- failures: dump the heap, then exit so systemd restarts us ---
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/var/lib/courseserver/dumps
-XX:+ExitOnOutOfMemoryError
-XX:ErrorFile=/var/log/courseserver/hs_err_pid%p.log
# --- logging: rotating GC log ---
-Xlog:gc*:file=/var/log/courseserver/gc.log:time,uptime,level,tags:filecount=5,filesize=10m
# --- application defaults ---
-Duser.timezone=UTC
-Dfile.encoding=UTF-8
-Dapp.env=prod
Verify the file before deploying it:
java @/etc/courseserver/jvm.options -XX:+PrintFlagsFinal -version \
| grep -E ' (MaxHeapSize|InitialHeapSize|MaxMetaspaceSize|MaxGCPauseMillis|ThreadStackSize|UseG1GC|ExitOnOutOfMemoryError) '
bool ExitOnOutOfMemoryError = true {product} {command line}
size_t InitialHeapSize = 1073741824 {product} {command line}
uintx MaxGCPauseMillis = 100 {product} {command line}
size_t MaxHeapSize = 1073741824 {product} {command line}
size_t MaxMetaspaceSize = 268435456 {product} {command line}
intx ThreadStackSize = 512 {pd product} {command line}
bool UseG1GC = true {product} {command line}
How it works:
- Fixed heap.
-Xms1g -Xmx1greserves the full heap at startup. Memory use stays flat, and you find out at boot, not at peak traffic, if the server is too small. - Room outside the heap.
-XX:MaxMetaspaceSize=256mcaps class metadata, and-Xss512khalves each thread stack. Together they keep total RAM use well under 2 GB. - Pause goal.
-XX:MaxGCPauseMillis=100asks G1 to keep pauses near 100 ms instead of the default 200 ms, which suits an HTTP API. G1 treats it as a target, not a guarantee. - Evidence on failure. A heap dump, a crash log (
%pbecomes the process ID) and the GC log are all written to known folders before the JVM exits with code 3. - Checked before use. Every value shows
{command line}inPrintFlagsFinal, proving the file was parsed and nothing was misspelled. A misspelled-XXflag stops the JVM withUnrecognized VM option, so this check catches typos before a deploy.
Once these options are live, Java JVM Monitoring shows how to watch heap, GC and threads on the running server.