knaxuslearn · build · ship

Projects / Profiler agent / Phase 2

Phase 2 of 4 · about 2.5 hours

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.

Step 2.1: Options, and what happens when they are wrong (about 30 minutes)

Hard-coding the interval and the output file gets old quickly. An agent receives its options as one string, written after the = in the flag: -javaagent:agent.jar=interval=10,out=profile.collapsed. We parse it ourselves:

package prof;

/** Reads "interval=10,out=profile.collapsed" from the -javaagent option string. */
record Options(long intervalMs, String outFile) {
    static Options parse(String args) {
        long interval = 10;
        String out = "profile.collapsed";
        if (args != null && !args.isBlank()) {
            for (String part : args.split(",")) {
                String[] kv = part.split("=", 2);
                if (kv.length != 2) throw new IllegalArgumentException("bad option: " + part);
                switch (kv[0]) {
                    case "interval" -> interval = Long.parseLong(kv[1]);
                    case "out" -> out = kv[1];
                    default -> throw new IllegalArgumentException("unknown option: " + kv[0]);
                }
            }
        }
        return new Options(interval, out);
    }
}

Two choices are worth a look. A record gives us an immutable object with accessors for free. And an unknown option throws instead of being ignored, because a typo such as inteval=1 that silently runs with the default is a very quiet way to waste an afternoon.

What does the JVM do with an agent that throws in premain? Try an option that does not exist:

java -javaagent:agent.jar=speed=5 -cp work Workload
Exception in thread "main" java.lang.reflect.InvocationTargetException
Caused by: java.lang.IllegalArgumentException: unknown option: speed
Aborted
exit status: 134

The program never starts. The JVM treats a failing premain as fatal, and that is what we want here: a profiler that did not start should not look like a profiler that found nothing. (An agent loaded later with Attach, which we build in Phase 4, is different. A failing agentmain is ignored by the JVM, so an attached agent has to report its own errors.)

Step 2.2: Keep the whole stack (about 45 minutes)

Instead of counting the top frame, we now count the whole stack as one string. The innermost frame comes first in the array, but every profiling tool writes stacks root first, like a path: main;warm;append;ensureCapacity. So we reverse the array and join it with ;:

    /** The stack comes with the innermost frame first. We write the root first, joined by ';'. */
    static String collapse(StackTraceElement[] stack) {
        List<String> frames = new ArrayList<>(stack.length);
        for (StackTraceElement f : stack) frames.add(f.getClassName() + "." + f.getMethodName());
        Collections.reverse(frames);
        return String.join(";", frames);
    }

In sampleOnce the line that counted the top method becomes one line:

stacks.merge(collapse(stack), 1, Integer::sum);

Two stacks that are the same string are the same stack, so one Map<String, Integer> holds everything: each distinct stack and how many times we saw it. For our little program it ends up with only a handful of entries.

This a;b;c 17 format has a name, collapsed stacks. Brendan Gregg's FlameGraph tools call the step of turning raw stacks into one line each "folding", and almost every profiler can read or write the format. Because we produce it, our profiler can feed those tools without any glue.

Step 2.3: Total time and self time (about 45 minutes)

With whole stacks we can answer two different questions about each method:

  • Self time: how often was it the innermost frame? That is the time spent in the method's own code.
  • Total time: how often was it anywhere on the stack? That is the time of the method plus everything it called.

A method with high total but low self time is a method that mostly waits for its callees. A method with high self time is where the CPU actually burns. Both matter, and they say different things. Here is the code:

    /** One line per method: total = samples with the method anywhere on the stack, self = on top. */
    static void print(Map<String, Integer> stacks) {
        int samples = stacks.values().stream().mapToInt(Integer::intValue).sum();
        Map<String, Integer> total = new HashMap<>();
        Map<String, Integer> self = new HashMap<>();
        for (Map.Entry<String, Integer> e : stacks.entrySet()) {
            String[] frames = e.getKey().split(";");
            Set<String> seen = new HashSet<>();
            for (String f : frames) {
                if (seen.add(f)) total.merge(f, e.getValue(), Integer::sum);
            }
            self.merge(frames[frames.length - 1], e.getValue(), Integer::sum);
        }
        System.err.println("prof: " + samples + " samples");
        System.err.println("  total   self  method");
        total.entrySet().stream()
                .sorted((a, b) -> b.getValue() - a.getValue())
                .limit(8)
                .forEach(e -> System.err.printf("  %5.1f%% %5.1f%%  %s%n",
                        100.0 * e.getValue() / samples,
                        100.0 * self.getOrDefault(e.getKey(), 0) / samples,
                        e.getKey()));
    }

One detail deserves attention. A sample counts once toward the total of a method even when the method appears several times in the same stack. That is the Set<String> seen inside the loop. Without it, a recursive method such as a naive Fibonacci would report a total above 100%.

Rebuild and run:

bash build.sh
java -javaagent:agent.jar=interval=10,out=profile.collapsed -cp work Workload
done true
prof: 280 samples
  total   self  method
  100.0%   0.0%  Workload.main
   60.4%  60.4%  Workload.hot
   29.6%   9.6%  Workload.warm
   20.0%   0.4%  java.lang.StringBuilder.append
   19.6%   0.4%  java.lang.AbstractStringBuilder.append
    9.6%   9.6%  java.lang.Integer.getChars
    9.6%   9.3%  java.lang.AbstractStringBuilder.ensureCapacityInternal
    9.6%   9.6%  Workload.cold

Now Workload.warm shows its real total of about 30%, and its self column shows how much of that was its own code. The rest is the StringBuilder calls below it. Workload.main has a total near 100% and a self near 0%, which is what a method that only calls other methods looks like. This is the picture Phase 1 could not give us.

Step 2.4: Write the stacks to a file (about 30 minutes)

The last piece writes the collapsed stacks to the file named by out=:

    /** The "collapsed stacks" format: one line per distinct stack, then a space and its count. */
    static void writeCollapsed(Map<String, Integer> stacks, String file) {
        try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(Path.of(file)))) {
            for (Map.Entry<String, Integer> e : new TreeMap<>(stacks).entrySet()) {
                out.println(e.getKey() + " " + e.getValue());
            }
        } catch (IOException ex) {
            System.err.println("prof: cannot write " + file + ": " + ex.getMessage());
        }
    }

The TreeMap sorts the lines, so two runs of the same program produce files you can compare with diff. Look at what we wrote:

cat profile.collapsed | cut -c1-120
Workload.main;Workload.cold 27
Workload.main;Workload.hot 169
Workload.main;Workload.warm 27
Workload.main;Workload.warm;java.lang.StringBuilder.append 1
Workload.main;Workload.warm;java.lang.StringBuilder.append;java.lang.AbstractStringBuilder.append 1
Workload.main;Workload.warm;java.lang.StringBuilder.append;java.lang.AbstractStringBuilder.append;java.lang.AbstractStri
Workload.main;Workload.warm;java.lang.StringBuilder.append;java.lang.AbstractStringBuilder.append;java.lang.AbstractStri
Workload.main;Workload.warm;java.lang.StringBuilder.append;java.lang.AbstractStringBuilder.append;java.lang.Integer.getC
Workload.main;java.lang.invoke.MethodHandleNatives.linkCallSite;java.lang.invoke.MethodHandleNatives.linkCallSiteImpl;ja

Each line is one distinct stack, then a space, then its count. Add up the counts and you get the number of samples in the header. You now have the same data a commercial profiler keeps, in a plain text file you can read, sort and grep.