Fix OpenJDK Platform Binary High Memory & CPU Usage
In this article
Yes, you can reduce the high memory and CPU usage of the OpenJDK platform binary by adjusting JVM options, updating the JDK, and eliminating runaway threads.
What You’ll Need
- A Linux, macOS, or Windows machine where the problematic Java application runs.
- Administrative or sudo privileges to change system settings and restart services.
- Access to the Java application's start‑up scripts or service configuration files.
- Basic command‑line tools:
ps,top/htop,jcmd,jstack, andjmap. - Optional but helpful: a recent JDK installation (OpenJDK 11 or newer) and a text editor.
Step‑By‑Step
- Confirm the culprit. Run
top -p $(pgrep -f "java")or usehtopand look for a process namedjavaorjava.exethat shows unusually high %CPU or RES memory. Note its PID. - Gather a thread dump. Execute
jstack <PID> > thread_dump.txt. Open the file and search for threads stuck injava.lang.Thread.State: RUNNABLEor repeatedly calling the same method. This often points to an infinite loop or a busy‑wait. - Collect a heap snapshot. Run
jmap -dump:live,format=b,file=heap.hprof <PID>. Load the.hproffile into a tool such as Eclipse MAT or VisualVM to identify objects that dominate the heap (e.g., large collections, caches, or unclosed streams). - Check JVM flags. Print the current flags with
jcmd <PID> VM.flags. Look for memory‑related options like-Xmx,-Xms,-XX:MaxMetaspaceSize, or garbage‑collector settings that may be mis‑configured. - Adjust heap limits. If the process is consistently near the
-Xmxlimit, increase it modestly (e.g., from-Xmx2gto-Xmx3g) or, if the heap is oversized for the workload, lower it to force more frequent garbage collection. Add the flags to the start‑up script, for example:JAVA_OPTS="-Xms1g -Xmx2g -XX:+UseG1GC -XX:MaxGCPauseMillis=200" export JAVA_OPTS
- Enable a modern garbage collector. G1GC (the default in recent JDKs) handles large heaps efficiently. If the application still uses ParallelGC or CMS, replace the flag with
-XX:+UseG1GC. For low‑latency workloads, consider-XX:+UseZGC(available in JDK 15+). - Turn on Native Memory Tracking (NMT) for deeper insight. Restart the JVM with
-XX:NativeMemoryTracking=summary -XX:+PrintNMTStatistics. After a few minutes, runjcmd <PID> VM.native_memory summaryto see which native subsystems (e.g., thread stacks, code cache) consume the most memory. - Inspect thread pools. Many high‑CPU spikes arise from thread pools that create more threads than the machine can handle. Look for libraries (e.g.,
Executors.newFixedThreadPool) that use unbounded queues. If you find them, replace with a bounded queue and a sensiblemaximumPoolSize. - Update the JDK. Run
java -version. If you are on an older LTS release (e.g., OpenJDK 8) consider upgrading to OpenJDK 11 or 17, which include performance improvements and bug fixes for memory leaks in the runtime. - Apply application‑level fixes. Based on the thread dump and heap analysis, modify the code that creates large collections, forgets to close I/O streams, or holds references longer than needed. Common patterns include:
- Using
try‑with‑resourcesfor streams and sockets. - Calling
clear()on largeMaporListobjects after use. - Avoiding static caches that never expire.
- Using
- Restart the service. After applying flag changes or code updates, stop the Java process gracefully (e.g.,
systemctl stop myapporkill -SIGTERM <PID>) and start it again. Verify that CPU and memory consumption have dropped usingtoporhtop.
Common Mistakes
- Setting
-Xmxhigher than the physical RAM. The OS will start swapping, which appears as high CPU usage. - Disabling garbage collection entirely with
-XX:+DisableExplicitGCin hopes of saving cycles; this often backfires when the heap fills. - Changing flags in the wrong script (e.g., editing a user‑level wrapper but the service uses a systemd unit that overrides it).
- Relying on
jmap -heapfor live memory while the process is under heavy load; the snapshot can be inaccurate and may pause the application.
Tips
- Enable
-XX:+PrintGCDetails -XX:+PrintGCDateStampsand review the GC log withgcviewerorgceasy.ioto spot long pauses. - Use
jcmd <PID> VM.native_memory detailperiodically in production to catch gradual native‑memory growth before it becomes critical. - When using Docker, add
--ulimit memlock=-1:-1if you enable large native memory tracking, otherwise the JVM may abort. - Consider container‑aware flags such as
-XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeapif the Java process runs inside a Kubernetes pod.
Troubleshooting
If the steps above do not lower the usage, follow this escalation path:
- Restart the host. A fresh kernel clears any lingering memory fragmentation that can affect native allocations.
- Run a minimal Java program. Deploy a simple
HelloWorldjar with the same JVM flags. If it also consumes high CPU, the issue is likely at the JVM or OS level rather than the application. - Check for OS‑level limits. Verify
ulimit -a(Linux) or Resource Monitor (Windows) for limits on virtual memory, thread count, or file descriptors. - Inspect native libraries. If the application loads JNI code, a native memory leak can masquerade as Java heap growth. Use
valgrind --leak-check=fullon Linux to detect leaks in the native code. - Consult vendor bug databases. Search the OpenJDK bug tracker for the exact version you run; some releases have known memory‑leak bugs that are fixed in later patches.
- Consider a full reinstall. Remove the current JDK directory, purge configuration files, and install a clean copy from the official OpenJDK site. Back up any custom
jre/libextensions before removal.
Frequently Asked Questions
Why does the OpenJDK process show high RES memory but low heap usage?
RES includes native memory such as thread stacks, JIT compiled code, and NMT data. A leak in native code or an excessively large thread pool can inflate RES without affecting the Java heap.
Can I limit CPU usage of a Java process without affecting performance?
Use OS‑level cgroups (Linux) or Job Objects (Windows) to cap CPU shares. Adjusting GC pause targets and using a low‑latency collector (ZGC) can also reduce CPU spikes while keeping throughput acceptable.
Is -XX:+UseCompressedOops relevant for memory problems?
Compressed ordinary object pointers reduce heap overhead on 64‑bit JVMs with < 32 GB RAM. If you already run with a small heap, the flag is enabled by default and has little impact on high‑memory symptoms.
How often should I rotate GC logs?
Rotate every 24 hours or when the log exceeds 100 MB. This prevents disk‑space exhaustion and keeps analysis files manageable.
What does “Metaspace out of memory” mean in this context?
Metaspace stores class metadata. If many dynamic class loaders are created without being released, Metaspace can grow until the JVM throws an OOM. Set -XX:MaxMetaspaceSize to a reasonable limit and ensure class loaders are closed.
Do I need to restart the JVM after changing -Xmx?
Yes. Heap size flags are read only at JVM start‑up, so a full restart is required for the new limits to take effect.