Java Performance Profiling

3 minute read

Your app is slow. Where is the bottleneck? Profiling answers this question with data — not guessing. Here’s how to profile Java applications from development to production.


Types of Profiling

Type Finds Tools
CPU Hot methods, slow code paths async-profiler, JFR, VisualVM
Memory Allocation hotspots, GC pressure JFR, VisualVM, Eclipse MAT
Allocation Objects created per second, allocation sites JFR, async-profiler
Lock/Thread Contention, deadlocks, blocked threads JFR, VisualVM

Java Flight Recorder (JFR)

JFR is built into the JDK (since Java 11, free since Java 11). Low overhead (~1%), safe for production.

Start Recording

# At startup
java -XX:StartFlightRecording=duration=60s,filename=recording.jfr -jar app.jar

# On a running JVM
jcmd <PID> JFR.start duration=60s filename=recording.jfr

# Continuous recording (dump on demand)
java -XX:StartFlightRecording=disk=true,maxage=1h,maxsize=500m -jar app.jar
jcmd <PID> JFR.dump filename=snapshot.jfr

Analyze with JDK Mission Control (JMC)

jmc    # opens GUI, File → Open → recording.jfr

Key views:

  • Automated Analysis — highlights top issues
  • Method Profiling — CPU hotspots
  • Memory — allocation rates, GC events
  • Threads — lock contention, blocked threads
  • I/O — file and socket operations

async-profiler

The best sampling profiler for Java — low overhead, production-safe, generates flame graphs.

# Install
# macOS
brew install async-profiler

# Linux — download from https://github.com/async-profiler/async-profiler

# CPU profiling for 30 seconds
asprof -d 30 -f cpu-flame.html <PID>

# Allocation profiling
asprof -d 30 -e alloc -f alloc-flame.html <PID>

# Wall-clock profiling (includes sleeping/waiting time)
asprof -d 30 -e wall -f wall-flame.html <PID>

Flame Graphs

A flame graph shows where your app spends time — wider bars = more CPU time.

┌──────────────────────────────────────────────────────┐
│                    main()                             │
├──────────────────────────┬───────────────────────────┤
│    processOrders()       │    generateReport()        │
├───────────┬──────────────┤                           │
│ fetchDB() │ calculate()  │                           │
├───────────┤              │                           │
│  query()  │              │                           │
└───────────┴──────────────┴───────────────────────────┘

Reading: processOrders() uses ~60% CPU. Within it, fetchDB() is the hotspot. Optimize there first.


VisualVM

Free GUI profiler — good for development, not production.

jvisualvm   # bundled with some JDK distributions
# Or download from https://visualvm.github.io
  1. Connect to local/remote JVM
  2. Monitor tab — CPU, heap, threads overview
  3. Sampler — CPU hotspots and memory allocations
  4. Profiler — detailed instrumentation (higher overhead)

JMH — Java Microbenchmark Harness

For measuring specific code performance accurately. JMH handles JIT warmup, dead code elimination, and measurement methodology.

Setup

<dependency>
    <groupId>org.openjdk.jmh</groupId>
    <artifactId>jmh-core</artifactId>
    <version>1.37</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.openjdk.jmh</groupId>
    <artifactId>jmh-generator-annprocess</artifactId>
    <version>1.37</version>
    <scope>test</scope>
</dependency>

Example Benchmark

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 5, time = 1)
@Fork(2)
@State(Scope.Thread)
public class StringConcatBenchmark {

    private static final int SIZE = 100;

    @Benchmark
    public String stringConcat() {
        String result = "";
        for (int i = 0; i < SIZE; i++) {
            result += "item" + i;    // creates new String each iteration
        }
        return result;
    }

    @Benchmark
    public String stringBuilder() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < SIZE; i++) {
            sb.append("item").append(i);
        }
        return sb.toString();
    }
}
Benchmark                          Mode  Cnt     Score   Error  Units
StringConcatBenchmark.stringConcat avgt   10  4523.456 ± 123  ns/op
StringConcatBenchmark.stringBuilder avgt  10   387.234 ±  12  ns/op

StringBuilder is 11× faster — now you have proof, not opinion.

Running

mvn clean install
java -jar target/benchmarks.jar

Production Profiling Checklist

Tool Overhead Production Safe? Best For
JFR ~1% ✅ Yes All-purpose production profiling
async-profiler ~1% ✅ Yes CPU/alloc flame graphs
VisualVM 5–15% ❌ Dev only Quick exploration
JProfiler 5–10% ⚠️ Careful Detailed dev profiling

Common Performance Anti-Patterns

Anti-Pattern Problem Fix
String concatenation in loops Creates N objects StringBuilder
Autoboxing in hot paths Integer.valueOf() allocations Use primitives
Logging with string concat Concat even when level disabled log.debug("x={}", x)
Synchronized everywhere Thread contention ConcurrentHashMap, lock-free structures
N+1 database queries N extra queries for related data JOIN or batch fetch
Creating objects in hot loops GC pressure Object pooling or reuse

Profiling Workflow

1. Reproduce the issue (load test, specific request)
2. Start JFR recording (or async-profiler)
3. Generate flame graph
4. Identify the widest bars (hotspots)
5. Optimize the hotspot
6. Measure again (JMH for micro, load test for macro)
7. Verify improvement

Common Mistakes

Mistake Problem Fix
Profiling in dev, not prod Different load, JIT, data Use JFR/async-profiler in production
Optimizing without measuring May optimize cold code Profile first, optimize hotspots
Microbenchmarking without JMH JIT, dead code, warmup issues Always use JMH
Profiling with IDE profiler in prod High overhead Use JFR or async-profiler

Key Takeaways

  1. JFR is the gold standard for production profiling — built-in, ~1% overhead.
  2. async-profiler flame graphs show you exactly where CPU time goes.
  3. JMH for microbenchmarks — don’t trust System.nanoTime() loops.
  4. Profile first, optimize hotspots — don’t guess.
  5. Top anti-patterns: string concat in loops, N+1 queries, autoboxing.

What’s Next?

Next: GraalVM and Native Image — ahead-of-time compilation for instant startup and low memory.

Updated: