JVM tuning can dramatically improve performance. A practical cheat sheet.
Memory¶
-Xms4g -Xmx4g -XX:MaxMetaspaceSize=512m
Garbage Collectors¶
-XX:+UseG1GC -XX:+UseZGC # Java 17+ -XX:+UseShenandoahGC
GC Logging¶
-Xlog:gc*:file=gc.log:time,uptime
JFR¶
jcmd
Diagnostics¶
jstack
Containers¶
-XX:MaxRAMPercentage=75.0
Rules¶
- Heap = 50-75% RAM
- Xms = Xmx
- G1GC for most workloads
- ZGC for ultra-low latency
Choosing a Garbage Collector¶
G1GC is the default GC since Java 9 and a good choice for most applications. It divides the heap into regions and collects regions with the most garbage first. ZGC (Java 17+) offers ultra-low latency with GC pauses under 1ms, ideal for real-time systems and latency-sensitive microservices. Shenandoah GC offers similar characteristics to ZGC and is available in OpenJDK.
Java Flight Recorder (JFR) is a production profiler with minimal overhead (typically under 1%). It records CPU samples, allocations, GC events, I/O, and thread activity. Combining JFR with JDK Mission Control provides detailed performance analysis without needing to reproduce the problem. For containerized environments, always set -XX:MaxRAMPercentage instead of fixed -Xmx values so the JVM properly adapts to container memory limits.
Tip¶
Always measure before and after changes. JFR is the best tool for Java performance analysis.