Profiling
suggest changeProfiling answers the question "where does my program actually spend its time and memory?". Guessing is almost always wrong: the slow part is rarely the clever algorithm you were worried about, and usually something like a regex compiled in a loop, a hidden boxing conversion or a lock everyone waits on.
Kotlin on the JVM compiles to ordinary bytecode, so every JVM profiler works with it. This article covers:
- quick measurements in code with
kotlin.timeandThreadMXBean - JDK Flight Recorder (JFR): starting recordings,
jcmd, thejfrtool, recording from code, custom events - async-profiler and flame graphs
- the IntelliJ IDEA profiler
- memory profiling: allocation profiling, heap histograms and heap dumps
- thread dumps and lock contention
- how Kotlin constructs (lambdas, inline functions, coroutines) look in a profile
Writing fast code (benchmarking with JMH, avoiding boxing, choosing collections) is a separate topic. This article is about finding out what to fix.
The tools at a glance
| Tool | Ships with | Good for |
|---|---|---|
measureTime, ThreadMXBean |
Kotlin stdlib, JDK | timing and counting allocations of one block of code |
JDK Flight Recorder (-XX:StartFlightRecording, jfr) |
JDK 11+ | low-overhead CPU, allocation, GC, lock and I/O profiling, safe in production |
| JDK Mission Control (JMC) | separate download | GUI for exploring .jfr files |
jcmd |
JDK | starting/stopping JFR, heap histograms, heap and thread dumps of a running process |
| async-profiler | separate download (Linux, macOS) | accurate CPU, wall-clock, allocation and lock profiles, flame graphs |
| IntelliJ IDEA profiler | IntelliJ IDEA | one-click JFR or async-profiler profiling with results in the editor |
| VisualVM, Eclipse MAT | separate download | live monitoring, heap dump analysis |
| Android Studio Profiler, Perfetto | Android SDK | CPU, memory and system traces on Android |
A program to profile
Throughout the article we use a small word counter with two typical performance bugs: a Regex constructed on every call and a string built with += in a loop.
// Main.kt
fun normalize(word: String): String =
word.lowercase().replace(Regex("[^a-z0-9]"), "") // compiles the regex on every call
fun countWords(words: List<String>): Map<String, Int> {
val counts = HashMap<String, Int>()
for (w in words) {
val n = normalize(w)
if (n.isNotEmpty()) counts[n] = (counts[n] ?: 0) + 1
}
return counts
}
fun report(counts: Map<String, Int>): String {
var out = ""
for ((word, n) in counts.entries.sortedByDescending { it.value }.take(2_000)) {
out += "$word: $n\n" // copies the whole string every iteration
}
return out
}
fun generateWords(n: Int): List<String> {
val vocabulary = List(5_000) { i -> "Word$i," }
return List(n) { vocabulary[(it * 7919L % vocabulary.size).toInt()] }
}
fun main() {
val words = generateWords(3_000_000)
val counts = countWords(words)
val text = report(counts)
println("distinct=${counts.size} reportLines=${text.count { it == '\n' }}")
}
distinct=5000 reportLines=2000
The outputs in this article come from one machine; your timings and sample counts will differ, but the proportions should be similar.
Quick measurements in code
Before reaching for a profiler, it is often enough to time the suspicious parts. kotlin.time has measureTime and measureTimedValue, which use a monotonic clock:
import kotlin.time.measureTime
import kotlin.time.measureTimedValue
fun main() {
val words = generateWords(3_000_000)
val (counts, countTime) = measureTimedValue { countWords(words) }
val reportTime = measureTime { report(counts) }
println("countWords: $countTime")
println("report: $reportTime")
}
countWords: 2.871536400s
report: 38.112300ms
Wall-clock time hides two things that often matter more: how much CPU the thread used (versus waiting on I/O or locks) and how much memory it allocated. The HotSpot-specific com.sun.management.ThreadMXBean exposes both for the current thread:
import com.sun.management.ThreadMXBean
import java.lang.management.ManagementFactory
import kotlin.time.measureTimedValue
val threadBean = ManagementFactory.getThreadMXBean() as ThreadMXBean
inline fun <T> profiled(label: String, block: () -> T): T {
val cpuStart = threadBean.currentThreadCpuTime // nanoseconds
val allocStart = threadBean.currentThreadAllocatedBytes // bytes
val (result, wall) = measureTimedValue(block)
val cpuMs = (threadBean.currentThreadCpuTime - cpuStart) / 1_000_000
val allocMb = (threadBean.currentThreadAllocatedBytes - allocStart) / (1024 * 1024)
println("$label: wall=${wall.inWholeMilliseconds} ms cpu=$cpuMs ms allocated=$allocMb MiB")
return result
}
fun main() {
val words = generateWords(3_000_000)
val counts = profiled("countWords") { countWords(words) }
profiled("report") { report(counts) }
}
countWords: wall=2840 ms cpu=2812 ms allocated=4391 MiB
report: wall=37 ms cpu=36 ms allocated=55 MiB
Over 4 GiB of garbage to count 3 million words is a strong hint, but it doesn't tell us which line allocates it. That's what profilers are for.
Two caveats for hand-made timing:
- The first run of any code is slow because it is interpreted before the JIT compiles it. Measure after a warm-up, or measure a long enough workload.
- One-off timings are noisy. For reliable comparisons of small pieces of code use a benchmark harness (JMH or kotlinx-benchmark) rather than
measureTimein a loop.
JDK Flight Recorder
JFR is built into the JDK. It samples running threads, records allocations, GC pauses, lock contention, file and socket I/O, and more, into a compact binary .jfr file. Its overhead is about 1% with the default settings and a few percent with the profile settings, so it is fine to leave on in production.
Recording from startup
Add -XX:StartFlightRecording to the JVM command line:
kotlinc Main.kt -include-runtime -d wordcount.jar
java -XX:StartFlightRecording=filename=wordcount.jfr,settings=profile -jar wordcount.jar
The recording is written to wordcount.jfr when the JVM exits. Useful options, separated by commas:
| Option | Meaning |
|---|---|
filename=app.jfr |
where to write the recording |
settings=profile |
more detailed sampling (10 ms CPU sampling, allocation stacks); default is lighter |
duration=60s |
stop after 60 seconds |
delay=30s |
start after 30 seconds, to skip startup and JIT warm-up |
maxage=10m, maxsize=200M |
keep only the most recent data (a ring buffer, good for long-running servers) |
With Gradle, add the flag to the run task (or to test to profile your tests):
// build.gradle.kts
tasks.named<JavaExec>("run") {
jvmArgs("-XX:StartFlightRecording=filename=build/run.jfr,settings=profile")
}
Recording a running process with jcmd
You don't need to restart a server to profile it. jcmd without arguments lists running JVMs, then you send commands by PID:
$ jcmd
41236 wordcount.jar
41301 jdk.jcmd/sun.tools.jcmd.JCmd
$ jcmd 41236 JFR.start name=prof settings=profile duration=60s filename=/tmp/prof.jfr
$ jcmd 41236 JFR.check # list active recordings
$ jcmd 41236 JFR.dump name=prof filename=/tmp/now.jfr # snapshot without stopping
$ jcmd 41236 JFR.stop name=prof
Analyzing with the jfr tool
Since JDK 21, jfr view prints ready-made reports in the terminal. jfr summary shows which events were recorded:
jfr summary wordcount.jfr
jfr view hot-methods wordcount.jfr
Java Methods that Execute the Most
Method Samples Percent
---------------------------------------------------------- ------- -------
java.util.HashMap.put(Object, Object) 18 18.95%
java.util.regex.Pattern.compile() 9 9.47%
java.util.regex.Pattern.inRange(int, int, int) 8 8.42%
java.util.regex.Pattern.expr(Pattern$Node) 8 8.42%
java.lang.StringLatin1.toLowerCase(String, byte[], Locale) 4 4.21%
...
(Output abridged; exact numbers differ between runs and machines.) Most of the hottest methods are regex and collection internals, not our code. That's typical: the top of the stack is in a library, and you have to look down the stack to find which of your calls got there. Other useful views:
| View | Shows |
|---|---|
hot-methods |
methods most often on top of the stack (CPU) |
allocation-by-site |
methods that allocate the most memory |
allocation-by-class |
types that are allocated the most |
gc / gc-pauses |
garbage collections and pause times |
contention-by-site |
where threads block on synchronized monitors |
thread-cpu-load |
CPU usage per thread |
Run jfr view without arguments to list all views. jcmd <pid> JFR.view hot-methods shows the same reports for a live process. For raw events use jfr print --events jdk.ExecutionSample wordcount.jfr, and for a GUI open the file in JDK Mission Control or IntelliJ IDEA (File | Open).
Recording and analyzing from Kotlin code
The jdk.jfr API lets a program profile a region of itself and inspect the results. This is handy in tests or when you want a profile of a single batch job step:
import jdk.jfr.Configuration
import jdk.jfr.Recording
import jdk.jfr.consumer.RecordedEvent
import jdk.jfr.consumer.RecordingFile
import java.nio.file.Path
fun frameName(e: RecordedEvent, i: Int): String? =
e.stackTrace?.frames?.getOrNull(i)?.method?.let { "${it.type.name}.${it.name}" }
fun main() {
val words = generateWords(3_000_000)
val file = Path.of("count.jfr")
Recording(Configuration.getConfiguration("profile")).use { recording ->
recording.start()
countWords(words)
recording.stop()
recording.dump(file)
}
val samples = RecordingFile.readAllEvents(file)
.filter { it.eventType.name == "jdk.ExecutionSample" }
// "inclusive" count: how often a method appears anywhere in the stack
val inclusive = samples
.flatMap { e -> e.stackTrace?.frames.orEmpty().map { "${it.method.type.name}.${it.method.name}" }.distinct() }
.groupingBy { it }.eachCount()
println("${samples.size} samples")
inclusive.entries.filter { it.key.startsWith("MainKt") }
.sortedByDescending { it.value }
.forEach { (method, n) -> println("%5.1f%% %s".format(100.0 * n / samples.size, method)) }
println("top frames under normalize():")
samples.filter { e -> e.stackTrace?.frames.orEmpty().any { it.method.name == "normalize" } }
.groupingBy { frameName(it, 0) }.eachCount()
.entries.sortedByDescending { it.value }.take(3)
.forEach { (method, n) -> println(" $n $method") }
}
281 samples
100.0% MainKt.main
100.0% MainKt.countWords
93.6% MainKt.normalize
top frames under normalize():
88 java.util.regex.Pattern.compile
41 java.util.regex.Pattern$CharPropertyGreedy.match
27 java.lang.String.toLowerCase
normalize accounts for over 90% of the time, and most of that is spent compiling the regex. The fix is to compile it once:
private val nonAlphanumeric = Regex("[^a-z0-9]")
fun normalize(word: String): String = word.lowercase().replace(nonAlphanumeric, "")
Running the profiled helper again confirms it: countWords: wall=610 ms cpu=598 ms allocated=1210 MiB. Always re-measure after a fix; that's the only way to know it worked.
Even though the JIT inlines small methods like normalize into their callers, JFR and the other profilers below still report them as separate frames, so the stacks match your source code.
Custom JFR events
You can define your own events to mark business operations in the recording. They appear in JMC and IntelliJ next to GC pauses and CPU samples, which makes it easy to see what the program was doing when something was slow:
import jdk.jfr.Category
import jdk.jfr.Event
import jdk.jfr.Label
import jdk.jfr.Name
@Name("com.example.BatchProcessed")
@Label("Batch Processed")
@Category("WordCount")
class BatchProcessedEvent : Event() {
@field:Label("Batch") var batch: Int = 0
@field:Label("Words") var words: Int = 0
}
fun processInBatches(words: List<String>) {
words.chunked(500_000).forEachIndexed { i, chunk ->
val event = BatchProcessedEvent()
event.begin() // start timestamp
countWords(chunk)
event.batch = i
event.words = chunk.size
event.commit() // records the event with its duration
}
}
Use @field: so the annotation lands on the backing field that JFR reads. Creating an event is cheap and commit() does nothing when no recording is running, so the instrumentation can stay in production code. List them with jfr print --events com.example.BatchProcessed app.jfr.
Streaming events
RecordingStream (JDK 14+) delivers events to callbacks while the program runs, which is useful for logging long GC pauses or exporting metrics:
import jdk.jfr.consumer.RecordingStream
import java.time.Duration
fun main() {
RecordingStream().use { rs ->
rs.enable("jdk.GarbageCollection")
rs.enable("jdk.CPULoad").withPeriod(Duration.ofSeconds(1))
rs.onEvent("jdk.GarbageCollection") { e ->
println("GC ${e.getString("name")} (${e.getString("cause")}): ${e.duration.toMillis()} ms")
}
rs.onEvent("jdk.CPULoad") { e ->
println("CPU machine=%.0f%%".format(e.getFloat("machineTotal") * 100))
}
rs.startAsync()
val counts = countWords(generateWords(3_000_000))
println("distinct=${counts.size}")
rs.stop() // flushes and delivers the remaining events
}
}
distinct=5000
GC G1New (G1 Evacuation Pause): 6 ms
GC G1New (G1 Evacuation Pause): 7 ms
GC G1New (G1 Evacuation Pause): 6 ms
...
Events are delivered in batches, about once a second, so a short program may finish before any callback runs. stop() (JDK 20+) delivers what's left; closing the stream without it drops those events. CPULoad lines appear only when the program runs longer than the 1-second period.
async-profiler and flame graphs
async-profiler is an open-source sampling profiler for Linux and macOS. It combines JVM stack walking with OS-level perf events, so it sees time spent in native code and the JVM itself (GC, JIT compiler) and doesn't suffer from safepoint bias. It produces interactive HTML flame graphs.
Attach to a running process with asprof:
asprof -d 30 -f cpu.html 41236 # CPU profile for 30 seconds
asprof -d 30 -e alloc -f alloc.html 41236 # where memory is allocated
asprof -d 30 -e wall -t -f wall.html 41236 # wall-clock, per thread: includes waiting
asprof -d 30 -e lock -f lock.html 41236 # lock contention
Or load it as an agent from startup:
java -agentpath:/opt/async-profiler/lib/libasyncProfiler.so=start,event=cpu,file=cpu.html \
-jar wordcount.jar
Which event to use:
cpuwhen the process is busy and you want to know what burns the CPU.wallwhen requests are slow but CPU is low: the profile shows threads waiting on I/O, locks,Thread.sleepor a database.allocwhen GC is frequent or allocation rate is high.lockwhen threads contend onsynchronizedorReentrantLock.
Reading a flame graph
Each box is a stack frame; its width is the share of samples in which that frame was on the stack. The y-axis is stack depth, with the entry point (main, Thread.run) at the bottom. Look for wide boxes: a wide frame whose children are much narrower is spending time in its own code ("self time"); a wide frame with one wide child is just passing the time down.
In the word counter, the flame graph shows MainKt.main → MainKt.countWords → MainKt.normalize spanning almost the full width, with a wide Pattern.compile tower on top of it.
The IntelliJ IDEA profiler
IntelliJ IDEA Ultimate has a built-in profiler that uses async-profiler and JFR behind the scenes:
- Click the gutter icon next to
fun main()or a test, then choose Profile with 'IntelliJ Profiler' (or use the Run | Profile menu for any run configuration, including Gradle tasks). - When the program exits (or you stop it), the profiler tool window opens with a Flame Graph, Call Tree, Method List and Timeline of threads.
- Switch between CPU Samples and Memory Allocations at the top.
- Right-click a frame and choose Jump to Source. The editor then shows per-line time and allocation hints in the gutter.
You can also attach to a running JVM from the Profiler tool window and capture memory snapshots (heap dumps) there. It is the quickest way to get from "this is slow" to the line responsible.
Memory profiling
There are two different memory questions, and they need different tools:
- Who allocates too much? High allocation rates cause frequent GCs and CPU overhead. Use allocation profiling: JFR (
jfr view allocation-by-site), async-profiler-e allocor IntelliJ's memory allocations view. - Who holds on to too much? Memory that is never freed (a leak) grows the heap until
OutOfMemoryError. Use heap histograms and heap dumps.
A heap histogram is a cheap, text-only overview of what's on the heap:
jcmd 41236 GC.class_histogram | head -8
num #instances #bytes class name (module)
-------------------------------------------------------
1: 1203885 124589376 [B (java.base@25)
2: 1201502 28836048 java.lang.String (java.base@25)
3: 5017 1270304 [Ljava.util.HashMap$Node; (java.base@25)
4: 15121 483872 java.util.HashMap$Node (java.base@25)
...
[B is byte[], the storage behind every String. Take two histograms a few minutes apart: classes whose counts only ever grow are leak suspects.
To find why objects are kept alive, take a heap dump and open it in Eclipse MAT, VisualVM or IntelliJ IDEA. They show the dominator tree and the path from a GC root to the leaking objects:
jcmd 41236 GC.heap_dump /tmp/heap.hprof
Always enable an automatic dump on OutOfMemoryError in production, so that you have evidence after a crash:
java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/dumps -jar app.jar
GC logs show how often collections happen and how long they pause; -Xlog:gc is enough for a first look:
[1.204s][info][gc] GC(12) Pause Young (Normal) (G1 Evacuation Pause) 412M->38M(1024M) 2.817ms
See Memory and garbage collection for how the heap and collectors work.
Thread dumps and contention
When a program hangs or is slow while the CPU is idle, look at what the threads are doing. A thread dump lists every thread with its state and stack:
jcmd 41236 Thread.print # same as jstack 41236
"worker-3" #31 prio=5 os_prio=0 cpu=812.45ms elapsed=14.20s tid=0x... nid=41290 waiting for monitor entry
java.lang.Thread.State: BLOCKED (on object monitor)
at Cache.get(Cache.kt:14)
- waiting to lock <0x000000071a8b2c10> (a Cache)
at MainKt.handle(Main.kt:42)
Take three dumps a few seconds apart: a thread stuck on the same frame in all of them is where the time goes. jcmd also detects and reports Java-level deadlocks at the end of Thread.print.
For virtual threads, which don't appear in Thread.print, use jcmd 41236 Thread.dump_to_file -format=json /tmp/threads.json. For coroutines, enable kotlinx-coroutines-debug and call DebugProbes.dumpCoroutines(), described in Stack traces.
To measure contention over time rather than at one moment, use JFR's jfr view contention-by-site or async-profiler with -e lock.
Kotlin code in a profile
Profilers show JVM class and method names, which differ from Kotlin source in predictable ways:
| In the profile | Kotlin source |
|---|---|
MainKt.countWords |
top-level function countWords in Main.kt (@file:JvmName changes the class name) |
MainKt$main$1.invoke |
a lambda inside main |
MainKt.report$default |
a call that used default argument values |
Order$Companion.parse |
a function in Order's companion object |
UserId.constructor-impl, UserId.toString-impl |
members of a value class UserId |
MainKt.findUser-a1b2c3d |
a function with a value class parameter (the name is mangled) |
MainKt$fetch$2.invokeSuspend |
the body of a suspend function or coroutine lambda |
kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run |
the dispatcher thread a coroutine runs on |
Other things to keep in mind:
- Inline functions disappear.
forEach,map,filter,let,use,synchronizedand your owninline funs are copied into the caller at compile time, so their cost is attributed to the calling function. That's why a profile may showcountWordswith high self time even though the work is "in" aforEach. - Coroutine stacks are split. A suspended coroutine has no thread stack. In a CPU profile you only see the part that runs between suspension points, rooted at the dispatcher's worker thread and
invokeSuspend, not at the code that launched it. Wall-clock profiles show idle dispatcher threads parked inCoroutineScheduler; that's waiting for work, not a problem. - Boxing shows up as
Integer.valueOfand similar calls when generic code works withInt,LongorDoublevalues. - Line numbers from inlined functions point into the inline function's source file with high line numbers; IntelliJ maps them back.
Profiling tips
- Profile a realistic workload. Use production-like data sizes and a release build. Profiling a 10-element test input mostly measures JIT warm-up.
- Let the JVM warm up before recording (
delay=in JFR), unless startup time is what you are investigating. - Pick the right kind of profile. CPU profiles don't show time spent waiting; use wall-clock profiles, thread dumps or JFR's I/O and lock events for latency problems.
- Beware of safepoint bias. Some samplers (old VisualVM sampling, repeated
jstack) can only record stacks at safepoints and over-report certain frames. JFR and async-profiler don't have this problem. Adding-XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepointsimproves line-level accuracy for async-profiler. - Fix one thing at a time and re-measure. Keep the before/after numbers. If the fix didn't move the numbers, revert it.
- Keep JFR on in production with a ring buffer (
maxage=) and dump it withjcmdwhen something goes wrong. A recording of the incident beats any reproduction attempt. - On Android, use the Android Studio Profiler (CPU, memory, energy) and Perfetto system traces on a real device in a release build; the emulator and debug builds have very different performance.