How do you troubleshoot high CPU, a memory leak or a hung application in production?
High CPU
top -H -p <pid>to find the hottest native thread id; convert it to hex.jcmd <pid> Thread.print(orjstack) and find the thread whosenidmatches. Take three dumps a few seconds apart to see if it stays in the same code.- Better: profile.
async-profilerproduces CPU flame graphs with very low overhead; Java Flight Recorder (jcmd <pid> JFR.start duration=60s filename=rec.jfr) is built in and safe in production (about 1% overhead). - Common causes: infinite loops, regex backtracking, GC thrashing (check GC first: high CPU in GC threads means a memory problem), busy-spin, serialisation of huge payloads.
Memory leak
- Confirm it: old-generation usage after full GC keeps rising over time.
- Capture a heap dump:
jcmd <pid> GC.heap_dump /tmp/heap.hprof, and set-XX:+HeapDumpOnOutOfMemoryErrorin production in advance. - Analyse in Eclipse MAT: the dominator tree and leak suspects report show what retains the most memory; "path to GC roots" shows why it is still reachable.
- Typical culprits: unbounded caches or static maps, listeners never removed,
ThreadLocals on pooled threads, unclosed resources, huge sessions, Hibernate first-level cache in a long batch.
Hung application or slow requests
- Thread dumps show threads
BLOCKEDon a lock (contention or deadlock) orWAITINGon a connection pool (pool exhaustion, often from a slow downstream or leaked connections). - Check HikariCP metrics (
hikaricp.connections.pending), outbound HTTP client pools and timeouts. Missing timeouts are the most common cause of production hangs.
Make it observable before it breaks
Metrics (heap, GC pauses, thread states, pool usage), structured logs with trace IDs, distributed tracing, and continuous profiling.
Follow-up questions interviewers ask
Try answering each one before you open it.
How do you take diagnostics from a JVM running in Kubernetes?
kubectl exec into the pod and use jcmd if the image has a JDK; with a JRE-only image, attach an ephemeral debug container sharing the process namespace (kubectl debug -it pod --image=eclipse-temurin:21-jdk --target=app). Copy the files out with kubectl cp. Write heap dumps to a mounted volume, since the container filesystem disappears if the pod is OOMKilled and restarted.
What is the difference between a thread dump and a heap dump?
A thread dump is a snapshot of every thread's stack and state (RUNNABLE, BLOCKED, WAITING) and the locks held; it is small, fast to take and diagnoses CPU, hangs and deadlocks. A heap dump is a snapshot of every object in the heap; it is large (about the heap size), pauses the JVM while it is written and diagnoses memory problems.