Profiling
suggest changeA profiler tells you where a program actually spends its time and memory. It's easy to guess wrong about this. In Java, the JIT compiler inlines and reorders code, and the garbage collector runs alongside your threads, so measure before you optimize.
The JDK comes with everything you need:
- JDK Flight Recorder (JFR): a low-overhead (about 1-2%) profiler built into the JVM. It is safe to keep running in production.
jfr: a command-line tool that prints and summarizes recordings.jcmd: sends diagnostic commands to a running JVM, such as thread dumps, heap histograms, heap dumps and starting or stopping JFR.java.lang.management/jdk.jfrAPIs: let you collect the same data from inside your program.
All examples were run on JDK 25. See Benchmarks and Simple JMH example for micro-benchmarking, and An evidence-based approach to Java performance tuning for where profiling fits in the tuning process.
Manual timing with System.nanoTime
The simplest profiler is a stopwatch. Use System.nanoTime() because it is monotonic. System.currentTimeMillis() follows the wall clock and can jump.
import java.util.concurrent.TimeUnit;
public class Timing {
static long sumSquares(int n) {
long sum = 0;
for (int i = 0; i < n; i++) sum += (long) i * i;
return sum;
}
static String concat(int n) {
String s = "";
for (int i = 0; i < n; i++) s += i % 10;
return s;
}
public static void main(String[] args) {
long t0 = System.nanoTime();
long r1 = sumSquares(2_000_000);
long t1 = System.nanoTime();
int len = concat(50_000).length();
long t2 = System.nanoTime();
System.out.printf("sumSquares: %d ms (result %d)%n",
TimeUnit.NANOSECONDS.toMillis(t1 - t0), r1);
System.out.printf("concat: %d ms (length %d)%n",
TimeUnit.NANOSECONDS.toMillis(t2 - t1), len);
}
}
sumSquares: 4 ms (result 2666664666667000000)
concat: 425 ms (length 50000)
Timing like this works for coarse questions ("is the slow part the database call or the JSON parsing?"). It can't tell you why a method is slow, and it doesn't scale to a large program. For that you need a sampling profiler.
Recording a profile with JDK Flight Recorder
This program has three typical hotspots: quadratic string concatenation, a CPU-bound loop, and heavy allocation from boxing:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Hot {
// slow: O(n^2) because of repeated String concatenation
static String buildReport(int lines) {
String report = "";
for (int i = 0; i < lines; i++) {
report += "line " + i + "\n";
}
return report;
}
// CPU-bound: naive prime check
static int countPrimes(int limit) {
int count = 0;
for (int n = 2; n < limit; n++) {
boolean prime = true;
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) { prime = false; break; }
}
if (prime) count++;
}
return count;
}
// allocation-heavy: boxes millions of Integers
static long sumBoxed(int n, Random rnd) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) list.add(rnd.nextInt(1000));
long sum = 0;
for (Integer v : list) sum += v;
return sum;
}
public static void main(String[] args) {
Random rnd = new Random(42);
long start = System.currentTimeMillis();
long checksum = 0;
while (System.currentTimeMillis() - start < Long.getLong("ms", 4000)) {
checksum += buildReport(5_000).length();
checksum += countPrimes(200_000);
checksum += sumBoxed(1_000_000, rnd);
}
System.out.println("checksum " + checksum);
}
}
To start a recording when the JVM starts, use -XX:StartFlightRecording. The profile settings sample more often and collect more events than the default settings:
$ javac -d out Hot.java
$ java -XX:StartFlightRecording=filename=hot.jfr,settings=profile -cp out Hot
[0.348s][info][jfr,startup] Started recording 1. No limit specified, using maxsize=250MB as default.
[0.348s][info][jfr,startup]
[0.348s][info][jfr,startup] Use jcmd 8900 JFR.dump name=1 to copy recording data to file.
checksum 31973950594
When the program exits, the recording is written to hot.jfr. jfr summary lists which events it contains:
$ jfr summary hot.jfr
Version: 2.1
Chunks: 1
Start: 2026-10-17 19:31:11 (UTC)
Duration: 4 s
Event Type Count Size (bytes)
=============================================================
jdk.GCPhaseParallel 10566 235861
jdk.PromoteObjectInNewPLAB 3373 53597
jdk.ObjectAllocationSample 1128 15657
...
jdk.ExecutionSample 319 2871
...
jdk.ExecutionSample events are CPU samples. Every 10-20 ms, JFR records the stack trace of each running Java thread.
Analyzing a recording with jfr view
jfr view has dozens of built-in reports (jfr help view lists them). hot-methods shows the methods that appear most often at the top of the stack:
$ jfr view hot-methods hot.jfr
Java Methods that Execute the Most
Method Samples Percent
--------------------------------------------------------------------------------------------------- ------- -------
jdk.internal.util.DecimalDigits.uncheckedGetCharsLatin1(int, int, byte[]) 88 27.59%
Hot.countPrimes(int) 83 26.02%
java.lang.Integer.valueOf(int) 80 25.08%
java.lang.String$$StringConcat.0x0000000085045400.prepend(int, byte, byte[], String[], String, int) 19 5.96%
Hot.sumBoxed(int, Random) 19 5.96%
java.lang.invoke.DirectMethodHandle$Holder.invokeSpecial(Object, Object, Object, int) 12 3.76%
java.util.ArrayList.add(Object, Object[], int) 7 2.19%
...
Read it this way:
DecimalDigits.uncheckedGetCharsLatin1andStringConcat.prependare JDK internals of+on strings. They come frombuildReport, which copies the whole report on every iteration.Hot.countPrimesis pure computation in our own code.Integer.valueOfis autoboxing insumBoxed.
Allocation views show what fills the heap and causes GC work:
$ jfr view allocation-by-class hot.jfr
Allocation by Class
Object Type Allocation Pressure
----------------------------------------------------------- -------------------
byte[] 68.98%
java.lang.Integer 23.69%
java.lang.Object[] 7.15%
java.lang.String 0.18%
java.util.ArrayList$Itr 0.00%
$ jfr view gc-pauses hot.jfr
GC Pauses
---------
Total Pause Time: 307 ms
Number of Pauses: 10
Minimum Pause Time: 3.21 ms
Median Pause Time: 29.2 ms
...
Maximum Pause Time: 53.3 ms
Other useful views: allocation-by-site, contention-by-site (lock contention), exception-count, file-reads-by-path, thread-cpu-load, gc and memory-leaks-by-class. To see full stack traces, print the raw events:
$ jfr print --events jdk.ExecutionSample --stack-depth 4 hot.jfr
...
jdk.ExecutionSample {
startTime = 21:31:11.278 (2026-10-17)
sampledThread = "main" (javaThreadId = 3)
state = "STATE_RUNNABLE"
stackTrace = [
Hot.countPrimes(int) line: 20
Hot.main(String[]) line: 43
]
}
...
For graphical analysis (flame graphs, call trees, an automated rules report), open the .jfr file in JDK Mission Control, IntelliJ IDEA (Run > Open Profiler Snapshot) or VisualVM.
Exact method timing and tracing (JDK 25)
Sampling is statistical. JDK 25 added bytecode-instrumented method timing and tracing to JFR (JEP 520). You name the methods with a filter: a class (Hot), a method (Hot::countPrimes) or an annotation (@jakarta.ws.rs.GET). JFR then counts every call and measures it exactly:
$ java '-XX:StartFlightRecording:method-timing=Hot,filename=timing.jfr' -cp out Hot
checksum 29976124046
$ jfr view method-timing timing.jfr
Method Timing
Timed Method Invocations Minimum Time Average Time Maximum Time
---------------------------- ----------- ------------ ------------ ------------
Hot.main(String[]) 1 4.05 s 4.05 s 4.05 s
Hot.buildReport(int) 60 9.040000 ms 30.300000 ms 82.500000 ms
Hot.sumBoxed(int, Random) 60 15.700000 ms 21.400000 ms 63.800000 ms
Hot.countPrimes(int) 60 13.100000 ms 15.600000 ms 20.100000 ms
Hot.<init>() 0 N/A N/A N/A
method-trace records one event per call, with its duration and stack trace. That shows who calls a method and how long each call takes:
$ java '-XX:StartFlightRecording:method-trace=Hot::countPrimes,filename=trace.jfr' -Dms=100 -cp out Hot
$ jfr print --events jdk.MethodTrace trace.jfr
jdk.MethodTrace {
startTime = 21:33:32.571 (2026-10-17)
duration = 19.9 ms
method = Hot.countPrimes(int)
eventThread = "main" (javaThreadId = 3)
stackTrace = [
Hot.main(String[]) line: 43
]
}
Instrumentation adds overhead to every call, so keep the filters narrow. Don't apply it to a hot inner method that is called millions of times.
Profiling from inside the program
The jdk.jfr API lets a program record itself. That's handy in tests, or when you want to profile one code path without restarting with JVM flags. This example records CPU samples while work() runs. It then reads the recording back and attributes each sample to the first frame from our own class, which also counts time spent in JDK methods called from our code:
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import jdk.jfr.Recording;
import jdk.jfr.consumer.RecordedEvent;
import jdk.jfr.consumer.RecordedFrame;
import jdk.jfr.consumer.RecordingFile;
public class InProcess {
static double work() {
double sum = 0;
for (int i = 0; i < 1000; i++) {
sum += slowSqrt(i) + fastSqrt(i);
}
return sum;
}
static double slowSqrt(int n) { // about 4x more work than fastSqrt
double s = 0;
for (int i = 0; i < 400_000; i++) s += Math.sqrt(n + i);
return s;
}
static double fastSqrt(int n) {
double s = 0;
for (int i = 0; i < 100_000; i++) s += Math.sqrt(n + i);
return s;
}
public static void main(String[] args) throws Exception {
Path file = Files.createTempFile("profile", ".jfr");
double result;
try (Recording r = new Recording()) {
r.enable("jdk.ExecutionSample").withPeriod(Duration.ofMillis(10));
r.start();
result = work();
r.stop();
r.dump(file);
}
// count samples by the first frame that belongs to our class
Map<String, Integer> counts = new HashMap<>();
int total = 0;
for (RecordedEvent e : RecordingFile.readAllEvents(file)) {
if (!e.getEventType().getName().equals("jdk.ExecutionSample")) continue;
total++;
for (RecordedFrame f : e.getStackTrace().getFrames()) {
if (f.getMethod().getType().getName().equals("InProcess")) {
counts.merge(f.getMethod().getName(), 1, Integer::sum);
break;
}
}
}
Files.delete(file);
System.out.printf("result %.0f, %d samples%n", result, total);
int t = total;
counts.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.forEach(en -> System.out.printf("%-10s %4d %5.1f%%%n",
en.getKey(), en.getValue(), 100.0 * en.getValue() / t));
}
}
result 190193622964, 92 samples
slowSqrt 73 79.3%
fastSqrt 19 20.7%
The 80/20 split matches the 4:1 ratio of work. Sampling needs enough samples to be accurate: at 10 ms per sample, a one-second run gives only about 100.
Custom JFR events
You can define your own events to record application-level operations next to the JVM's events. An event that is not enabled costs almost nothing, so you can leave the instrumentation in production code:
import jdk.jfr.Category;
import jdk.jfr.Event;
import jdk.jfr.Label;
import jdk.jfr.Name;
import jdk.jfr.StackTrace;
public class CustomEvent {
@Name("com.example.OrderProcessed")
@Label("Order Processed")
@Category({"Example", "Orders"})
@StackTrace(false)
static class OrderEvent extends Event {
@Label("Order Id") long orderId;
@Label("Items") int items;
}
static void processOrder(long id, int items) throws InterruptedException {
OrderEvent event = new OrderEvent();
event.begin();
Thread.sleep(items * 5L); // simulated work
event.orderId = id;
event.items = items;
event.commit(); // cheap no-op when the event is disabled
}
public static void main(String[] args) throws Exception {
for (int i = 1; i <= 5; i++) processOrder(1000 + i, i * 3);
System.out.println("done");
}
}
$ java -XX:StartFlightRecording=filename=orders.jfr -cp out CustomEvent
$ jfr view com.example.OrderProcessed orders.jfr
Order Processed
Start Time Duration Event Thread Stack Trace Order Id Items
---------- -------- ---------------------- --------------------- -------- -----
21:32:03 15.9 ms main N/A 1,001 3
21:32:03 30.3 ms main N/A 1,002 6
21:32:03 45.6 ms main N/A 1,003 9
21:32:03 61.5 ms main N/A 1,004 12
21:32:03 75.5 ms main N/A 1,005 15
begin() and commit() measure the duration. Custom events show up in Mission Control's event browser and can be filtered by @Category.
Live monitoring with event streaming
RecordingStream delivers JFR events to callbacks while the program runs, a few times per second. You can use it to log slow GCs or lock contention, or to export metrics:
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import jdk.jfr.consumer.RecordingStream;
public class LiveStream {
public static void main(String[] args) throws Exception {
try (var rs = new RecordingStream()) {
rs.enable("jdk.GarbageCollection");
rs.enable("jdk.JavaMonitorEnter").withThreshold(Duration.ofMillis(10));
rs.onEvent("jdk.GarbageCollection", e -> System.out.printf(
"GC %-22s %-30s %6.1f ms%n",
e.getString("name"), e.getString("cause"),
e.getDuration().toNanos() / 1e6));
rs.onEvent("jdk.JavaMonitorEnter", e -> System.out.printf(
"thread %s blocked %d ms on %s%n",
e.getThread("eventThread").getJavaName(),
e.getDuration().toMillis(),
e.getClass("monitorClass").getName()));
rs.startAsync();
generateGarbage();
contendLock();
Thread.sleep(1500); // let the stream flush the last events
}
}
static void generateGarbage() {
List<byte[]> keep = new ArrayList<>();
for (int i = 0; i < 2_000; i++) {
keep.add(new byte[100_000]);
if (keep.size() > 200) keep.clear();
}
System.gc();
}
static final Object LOCK = new Object();
static void contendLock() throws InterruptedException {
Thread holder = Thread.ofPlatform().name("holder").start(() -> {
synchronized (LOCK) { sleep(200); }
});
sleep(50); // make sure holder owns the lock first
Thread waiter = Thread.ofPlatform().name("waiter").start(() -> {
synchronized (LOCK) { }
});
holder.join();
waiter.join();
}
static void sleep(long ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException(e); }
}
}
GC G1New G1 Evacuation Pause 5.8 ms
GC G1Full System.gc() 10.9 ms
thread waiter blocked 150 ms on java.lang.Object
The threshold drops short lock waits, so only the waits that matter get reported.
Measuring CPU time and allocations per thread
com.sun.management.ThreadMXBean (an extension of the standard java.lang.management.ThreadMXBean) reports CPU time and allocated bytes for each thread. Wrapping a task with it gives a cheap, always-available profile of a single operation:
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import com.sun.management.ThreadMXBean;
public class ThreadCost {
static final ThreadMXBean THREADS =
(ThreadMXBean) ManagementFactory.getThreadMXBean();
static <T> T measure(String name, Supplier<T> task) {
long cpu0 = THREADS.getCurrentThreadCpuTime();
long alloc0 = THREADS.getCurrentThreadAllocatedBytes();
long wall0 = System.nanoTime();
T result = task.get();
long wall = System.nanoTime() - wall0;
long cpu = THREADS.getCurrentThreadCpuTime() - cpu0;
long alloc = THREADS.getCurrentThreadAllocatedBytes() - alloc0;
System.out.printf("%-10s wall %4d ms cpu %4d ms allocated %,12d bytes%n",
name, wall / 1_000_000, cpu / 1_000_000, alloc);
return result;
}
public static void main(String[] args) {
measure("boxed", () -> {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 5_000_000; i++) list.add(i);
return list.size();
});
measure("primitive", () -> {
int[] arr = new int[5_000_000];
for (int i = 0; i < arr.length; i++) arr[i] = i;
return arr.length;
});
measure("sleep", () -> {
try { Thread.sleep(300); } catch (InterruptedException e) { }
return 0;
});
for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
System.out.printf("%-28s collections %3d time %4d ms%n",
gc.getName(), gc.getCollectionCount(), gc.getCollectionTime());
}
}
}
boxed wall 134 ms cpu 109 ms allocated 153,844,040 bytes
primitive wall 12 ms cpu 15 ms allocated 20,000,032 bytes
sleep wall 301 ms cpu 0 ms allocated 3,528 bytes
G1 Young Generation collections 1 time 18 ms
G1 Concurrent GC collections 0 time 0 ms
G1 Old Generation collections 0 time 0 ms
When wall time is much higher than CPU time, the thread was waiting (I/O, locks, sleep), not computing. The boxed list allocates 7.7 times more memory than the int[]. On Windows, thread CPU time has a resolution of about 15 ms, so small values are rough. That's why primitive shows more CPU time than wall time.
Diagnosing a running JVM with jcmd
jcmd attaches to a JVM that's already running, with no restart and no special flags. jcmd -l lists Java processes:
$ jcmd -l
17080 Hot
24708 jdk.jcmd/sun.tools.jcmd.JCmd -l
A thread dump shows what each thread is doing right now, including its CPU time so far. A few dumps taken seconds apart make a poor man's profiler:
$ jcmd 17080 Thread.print
"main" #3 [31724] prio=5 os_prio=0 cpu=7000.00ms elapsed=8.69s tid=0x0000024acea0d180 nid=31724 runnable [0x000000c1d88fe000]
java.lang.Thread.State: RUNNABLE
at jdk.internal.util.DecimalDigits.uncheckedGetCharsLatin1(java.base@25.0.4.1/DecimalDigits.java:168)
at java.lang.StringConcatHelper.prepend(java.base@25.0.4.1/StringConcatHelper.java:716)
...
You can start, check and dump a JFR recording on a live process. A common production setup keeps a continuous recording with a bounded size and dumps it when something goes wrong:
$ java -XX:StartFlightRecording=name=continuous,maxage=30m,maxsize=200m,dumponexit=true,filename=exit.jfr -cp out Hot
$ jcmd 1972 JFR.check
1972:
Recording 1: name=continuous maxsize=200.0MB maxage=30m (running)
$ jcmd 1972 JFR.dump name=continuous filename=/tmp/snapshot.jfr
1972:
Dumped recording "continuous", 525.5 kB written to:
/tmp/snapshot.jfr
To profile a process that was started without JFR, use jcmd <pid> JFR.start settings=profile duration=60s filename=/tmp/rec.jfr. Other useful commands are GC.heap_info, VM.flags, VM.native_memory (requires -XX:NativeMemoryTracking=summary) and jcmd <pid> help for the full list.
Finding memory leaks
In Java, a memory leak is an object that is still reachable but no longer needed, typically sitting in a cache or a static collection that only grows (see Memory leaks in Java). This program leaks sessions and writes a heap dump with HotSpotDiagnosticMXBean:
import java.lang.management.ManagementFactory;
import java.util.HashMap;
import java.util.Map;
import com.sun.management.HotSpotDiagnosticMXBean;
public class Leak {
record Session(String user, byte[] data) {}
// bug: sessions are added but never removed
static final Map<Integer, Session> CACHE = new HashMap<>();
static void handleRequest(int id) {
CACHE.put(id, new Session("user" + id, new byte[10_000]));
}
public static void main(String[] args) throws Exception {
for (int i = 0; i < 20_000; i++) handleRequest(i);
var bean = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
bean.dumpHeap("leak.hprof", true); // true = only live (reachable) objects
System.out.println("heap dump written, sessions: " + CACHE.size());
Thread.sleep(60_000); // keep running so we can attach jcmd
}
}
heap dump written, sessions: 20000
A class histogram is the quickest first look. It counts live objects by class, and a count that keeps growing between runs points at the leak:
$ jcmd 18112 GC.class_histogram
18112:
num #instances #bytes class name (module)
-------------------------------------------------------
1: 48943 201286904 [B (java.base@25.0.4.1)
2: 261 1787440 [Ljdk.internal.vm.FillerElement; (java.base@25.0.4.1)
3: 28865 692760 java.lang.String (java.base@25.0.4.1)
4: 21050 673600 java.util.HashMap$Node (java.base@25.0.4.1)
5: 20000 480000 Leak$Session
6: 20134 322144 java.lang.Integer (java.base@25.0.4.1)
20,000 Leak$Session objects next to 200 MB of byte[] is the clue. To find who holds them, open the heap dump (leak.hprof, about 200 MB here) in Eclipse Memory Analyzer (MAT) or VisualVM. They show the dominator tree and the path to the GC root, which is Leak.CACHE in this case. You can also take a dump from outside with jcmd <pid> GC.heap_dump /tmp/app.hprof. To get one automatically when the heap runs out, start the JVM with -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp.
Heap dumps contain all data in memory, including passwords and personal data, so treat them as sensitive files.
Other profilers
- async-profiler (Linux, macOS): an open-source sampling profiler that combines Java and native stacks and produces flame graphs directly, for example
asprof -d 30 -f flame.html <pid>. It doesn't suffer from safepoint bias, and it can profile CPU, allocations, locks and wall-clock time. - IntelliJ IDEA Profiler: runs JFR or async-profiler from the IDE and shows flame graphs and call trees.
- VisualVM and JDK Mission Control: free GUIs for live monitoring, JFR analysis and heap dumps.
- JFR CPU-time sampling (JDK 25, experimental, Linux only):
-XX:StartFlightRecording=jdk.CPUTimeSample#enabled=truesamples based on actual CPU time rather than wall-clock intervals. View it withjfr view cpu-time-hot-methods.
Tips
- Profile a realistic workload with a warmed-up JVM. The first seconds are dominated by class loading and JIT compilation.
- Look at both CPU and allocation. Reducing allocation often speeds up the CPU profile too, because the GC has less work.
- Profile, change one thing, profile again. Use JMH to confirm micro-level improvements.
- Keep a continuous JFR recording in production (
maxage/maxsize). When an incident happens, you already have the data.