Sub topic 1
Start with a measurable goal
Prerequisites
Assume you know basic Java, can run applications from a command line, and understand threads and the heap. You should also be comfortable reading stack traces.
Start with a measurable goal
Performance work begins with a user-visible problem and a number. “Make it faster” is too vague. Define a target such as:
- Reduce p95 request latency from 800 ms to 300 ms.
- Increase throughput from 200 to 400 requests per second.
- Keep the heap below 2 GB.
- Reduce allocation rate without increasing error rate.
A percentile describes how fast most requests are. For example, p95 latency is the time below which 95% of requests finish. Record the workload, input size, JVM options, and environment before changing code.
What the JVM does while your code runs
The Java Virtual Machine (JVM) runs bytecode, manages objects in the heap, and uses a garbage collector (GC) to reclaim objects that are no longer reachable. A just-in-time (JIT) compiler observes frequently executed code and compiles it into optimized machine code.
These activities affect measurements. A GC pause can increase latency. JIT compilation can make later calls faster than earlier calls. Allocation-heavy code can consume CPU even when its own methods look simple.
Sampling and instrumentation: how profilers work
A sampling profiler periodically records the stack of a running thread. It adds little overhead and usually finds CPU hot spots, but short-lived work can be missed.
An instrumenting profiler adds tracking code to methods or events. It can count every call or allocation, but the tracking changes timing and increases overhead. Use sampling for an initial production investigation. Use instrumentation when you need precise call or allocation counts in a controlled environment.
First look with `jcmd`, `jstat` and `jstack`
Find the process ID, then collect focused evidence:
jcmd <pid> VM.flags
jstat -gcutil <pid> 1000
jstack <pid> > threads.txtjcmd queries JVM diagnostics. jstat reports changing GC and heap statistics. jstack captures thread stacks, which can reveal blocked or deadlocked threads. Avoid treating one snapshot as proof; compare observations with the performance goal.
Reading garbage collection logs
On Java 11, unified logging writes GC events to a file:
java -Xlog:gc*:file=gc.log:time,uptime,level,tags -jar app.jarLook for frequent collections, long pauses, and a heap that remains highly occupied after collections. Relate timestamps to request latency and allocation rate. Do not increase heap size automatically. A larger heap may reduce collection frequency while making eventual pauses longer.
Exercise
Which measurement should you choose first for an API that feels slow to users?
Show answer
Start with a latency target, usually a percentile such as p95, measured under a specified workload.