Projects / Profiler agent
Java · about 10 hours · 4 phases
Build a sampling profiler for the JVM
Suppose our service is slow and nobody knows why. We attach a profiler, it prints a list of methods with percentages, and we decide where to spend a week. That decision rests on those numbers, so it is worth knowing what they count and when they are wrong. In about 10 hours we will write a profiler as a Java agent, one layer at a time, and every layer ends with something you can run.
You work in four phases of about 2.5 hours each. By the end you will have a profiler that:
- loads into any Java program with one command line flag and samples its threads every few milliseconds,
- keeps whole call stacks and reports both "total" and "self" time per method,
- tells the difference between a thread that is burning CPU and a thread that is waiting,
- draws a flame graph, attaches to a program that is already running, and can be checked against the JDK's own profiler.
You need basic Java (classes, threads, Map, lambdas) and a terminal. Agents, stack traces and thread states are explained when they first show up.
If threads are new to you, read the Java concurrency tutorial first. Knowing what a thread is and how to start one is enough.
The four phases
Sample the stacks
You end with a Java agent that watches a program and prints its hottest methods when the program ends.
- 1.1 What a Java agent is30 min
- 1.2 The sampler thread40 min
- 1.3 Build it and run it40 min
- 1.4 Read the result, and find what is wrong40 min
Whole stacks and a report
You end with a report with a "total" and a "self" column per method, plus a file of stacks that other tools can read.
- 2.1 Options, and what happens when they are wrong30 min
- 2.2 Keep the whole stack45 min
- 2.3 Total time and self time45 min
- 2.4 Write the stacks to a file30 min
On the CPU, or waiting?
You end with a profiler with three modes, and the knowledge of which one answers which question.
- 3.1 A program with threads that do nothing40 min
- 3.2 Count only what really used CPU45 min
- 3.3 Wall-clock mode35 min
- 3.4 What does sampling cost?30 min
Flame graph, attach, and a cross-check
You end with a flame graph in a browser, a profile of a program that was already running, and a comparison against the JDK's own profiler.
- 4.1 Draw a flame graph40 min
- 4.2 Attach to a program that is already running40 min
- 4.3 Check it against the JDK's own profiler40 min
- 4.4 When not to trust it30 min