Projects / Profiler agent / Phase 1
Phase 1 of 4 · about 2.5 hours
Sample the stacks
You end with a Java agent that watches a program and prints its hottest methods when the program ends.
A profiler answers one question: where does the time go? The simplest way to answer is to look. Every few milliseconds you stop and ask each thread "what are you doing right now?", write the answer down, and repeat a few hundred times. A method that shows up in 60% of the answers probably uses about 60% of the time. This is called sampling, and it is how most profilers work.
Step 1.1: What a Java agent is (about 30 minutes)
We need our code to run inside the program we want to look at, without changing that program. The JVM has a door for this, called a Java agent. You pass -javaagent:agent.jar on the command line, and before the program's own main starts, the JVM calls a method named premain in your agent class. From there you can do anything the program itself could do, including starting threads.
An agent is a normal JAR file with one extra line in its manifest, saying which class holds premain:
Premain-Class: prof.Agent
The agent class is tiny. It starts a sampler thread and asks the JVM to run a report when the program exits:
package prof;
import java.lang.instrument.Instrumentation;
public final class Agent {
private Agent() {}
public static void premain(String args, Instrumentation inst) {
Sampler sampler = new Sampler(10);
sampler.start();
Runtime.getRuntime().addShutdownHook(new Thread(sampler::stopAndReport, "prof-report"));
}
}
Walk through it:
premain(String args, Instrumentation inst)is the entry point. We do not useinstyet. It is the handle for rewriting classes, which is what many other profilers do.Sampleris a thread we write in the next step. It runs next to the program's own threads.- A shutdown hook is a thread the JVM starts when the program is about to exit. We use it to print the result at the end.
Step 1.2: The sampler thread (about 40 minutes)
The core of the profiler is one JDK method, Thread.getAllStackTraces(). It returns a map from every live thread to its current stack trace, the list of method calls that led to where the thread is now. The first element is the innermost call, the method that is running at this moment.
First, the program we profile. Its three methods loop until a deadline, so each one burns a known amount of CPU:
public class Workload {
// Each method burns CPU for a fixed time, so we know the true split: 60 / 30 / 10.
static double hot(long ms) {
long end = System.nanoTime() + ms * 1_000_000;
double x = 0;
while (System.nanoTime() < end) {
for (int i = 1; i < 10_000; i++) x += Math.sqrt(i);
}
return x;
}
static int warm(long ms) {
long end = System.nanoTime() + ms * 1_000_000;
int n = 0;
while (System.nanoTime() < end) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 200; i++) sb.append(i).append(',');
n += sb.length();
}
return n;
}
static long cold(long ms) {
long end = System.nanoTime() + ms * 1_000_000;
long h = 17;
while (System.nanoTime() < end) {
for (int i = 0; i < 10_000; i++) h = h * 31 + i;
}
return h;
}
public static void main(String[] args) {
double sink = 0;
for (int round = 0; round < 3; round++) {
sink += hot(600);
sink += warm(300);
sink += cold(100);
}
System.out.println("done " + (sink != 0));
}
}
Now the sampler. Every intervalMs it takes a snapshot, then counts the innermost method of each busy thread:
private synchronized void sampleOnce() {
for (Map.Entry<Thread, StackTraceElement[]> e : Thread.getAllStackTraces().entrySet()) {
Thread t = e.getKey();
StackTraceElement[] stack = e.getValue();
if (t == this || stack.length == 0) continue;
if (t.getState() != Thread.State.RUNNABLE) continue;
ThreadGroup g = t.getThreadGroup();
if (g != null && g.getName().equals("system")) continue;
StackTraceElement top = stack[0];
counts.merge(top.getClassName() + "." + top.getMethodName(), 1, Integer::sum);
total++;
}
}
The rules, as the code writes them:
- We skip our own sampler thread. Profiling yourself only tells you that the profiler is running.
- We skip threads in the
systemgroup. Those are JVM helpers such as the signal dispatcher, and they would only add noise. - For now a thread counts as busy when its state is
RUNNABLE. Phase 3 shows why that is too simple. - The key is
Class.methodof the top frame. We count how often each key appears. sampleOnceissynchronizedso the report at the end sees a consistent map, not one that is half updated.
At the end we sort the counts and print the top five:
synchronized void stopAndReport() {
running = false;
System.err.println("prof: " + total + " samples");
counts.entrySet().stream()
.sorted((a, b) -> b.getValue() - a.getValue())
.limit(5)
.forEach(e -> System.err.printf(" %5.1f%% %s%n", 100.0 * e.getValue() / total, e.getKey()));
}
Step 1.3: Build it and run it (about 40 minutes)
Building an agent takes two small steps: compile the classes, then pack them with the manifest into a JAR. Put them in build.sh:
set -e
rm -rf out work agent.jar
mkdir out work
javac -d out src/prof/*.java
jar cfm agent.jar manifest.txt -C out prof
javac -d work Workload.java
Run the build, then start the program with the agent switched on:
bash build.sh
java -javaagent:agent.jar -cp work Workload
The program runs for about three seconds. This is what we got:
done true
prof: 280 samples
60.4% Workload.hot
12.9% Workload.warm
10.0% Workload.cold
7.9% java.lang.AbstractStringBuilder.ensureCapacityInternal
6.8% java.lang.Integer.getChars
If java says it cannot find the agent JAR, check that you are in the folder that holds agent.jar. If it complains about a missing Premain-Class, check that the manifest ends with a newline: the jar tool drops a last line that has none.
Your numbers will differ a little from ours. The sampler is a program too, and it takes a snapshot at slightly different moments each run. That is not a bug. It is the nature of sampling, and Step 1.4 looks at how much to trust it.
Step 1.4: Read the result, and find what is wrong (about 40 minutes)
Look at the report. Workload.hot shows about 60%, which matches the truth we built in. Workload.cold shows about 10%, which also matches. But where is Workload.warm? It should be 30%, and it shows a lot less. Instead the list contains AbstractStringBuilder.ensureCapacityInternal and Integer.getChars, methods we never wrote.
Nothing is lost. warm calls StringBuilder.append, which calls those JDK methods, and at the moment of a sample the processor is inside one of them. We only look at the innermost frame, so the time of warm is spread over its children. If a method does its work by calling other methods, a profiler that records only the top frame cannot say how much the caller costs.
Run it twice more and watch the numbers move:
prof: 279 samples
60.6% Workload.hot
12.9% Workload.warm
9.7% Workload.cold
prof: 278 samples
60.8% Workload.hot
13.7% Workload.warm
9.7% Workload.cold
The ranking holds, the decimals wobble. With about 280 samples in a run, one extra or missing sample moves a method by a third of a percentage point. A rule of thumb for a sampler: believe the order and the big gaps, and distrust differences of a point or two.
To fix the warm problem we need the whole stack, not just the top. That is Phase 2.