knaxuslearn · build · ship

Projects / Profiler agent / Phase 3

Phase 3 of 4 · about 2.5 hours

On the CPU, or waiting?

You end with a profiler with three modes, and the knowledge of which one answers which question.

So far we counted a thread when its state was RUNNABLE. That sounds like "running", but the JVM means something wider: the thread is not blocked on a lock and is not sleeping or waiting in Java code. Is a thread that waits for a network connection "running"? Let us find out.

Step 3.1: A program with threads that do nothing (about 40 minutes)

We add four background threads to the workload. Each one is idle in a different way:

    static void startBackground() {
        Object lock = new Object();
        daemon("sleeper", () -> {
            while (true) sleep(50);
        });
        daemon("holder", () -> {
            synchronized (lock) {
                sleep(60_000);
            }
        });
        sleep(50); // let the holder take the lock first
        daemon("waiter", () -> {
            synchronized (lock) {
                System.out.println("never printed");
            }
        });
        daemon("acceptor", () -> {
            try (ServerSocket server = new ServerSocket(0)) {
                server.accept();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }
  • sleeper calls Thread.sleep in a loop.
  • holder takes a lock and sleeps while holding it. waiter then tries to take the same lock and is blocked.
  • acceptor waits for a client to connect to a server socket that nobody ever connects to.

None of them uses the CPU. Now a mode switch, so the sampler can decide in three ways which threads count:

package prof;

/** Which threads count as "busy" at the moment of a sample. */
enum Mode {
    /** Any thread whose state is RUNNABLE. Cheap, but a thread waiting inside native I/O counts too. */
    RUNNABLE,
    /** Only threads whose CPU time moved since the last sample. */
    CPU,
    /** Every thread, whatever it is doing. Shows where time goes, waiting included. */
    WALL
}

We also put the thread's name at the root of every stack, as [acceptor];java.net..., so the report can show a share per thread. Run the old rule, mode=runnable:

java -javaagent:agent.jar=mode=runnable -cp work Workload
done true
prof: 559 samples
  thread [acceptor]  49.9%
  thread [main]      49.9%
  thread [sleeper]    0.2%
  total   self  method
   50.1%   0.0%  java.lang.Thread.runWith
   50.1%   0.0%  java.lang.Thread.run

Half of all samples blame sun.nio.ch.Net.accept, a thread that is doing nothing at all. The JVM reports a thread inside a native call, such as waiting on a socket, as RUNNABLE, because from the JVM's point of view it has not blocked on a Java lock. A profiler that trusts this state will send you to optimize code that is simply waiting. This is a classic way for a profile to mislead you, and it is very easy to fall into.

Step 3.2: Count only what really used CPU (about 45 minutes)

The operating system keeps a counter of CPU time for every thread, and Java can read it through ThreadMXBean. The trick is to compare it with the value from the previous sample: if the thread's CPU time has not moved, it was not on the CPU, whatever its state says.

    private boolean counts(Thread t) {
        return switch (mode) {
            case RUNNABLE -> t.getState() == Thread.State.RUNNABLE;
            case WALL -> true;
            case CPU -> movedOnCpu(t);
        };
    }

    /** True when the thread used a good share of one interval since we last looked. */
    private boolean movedOnCpu(Thread t) {
        long now = threads.getThreadCpuTime(t.threadId());
        if (now < 0) return false;
        Long before = lastCpuNanos.put(t.threadId(), now);
        return before != null && now - before >= intervalMs * 1_000_000 / 4;
    }

Walk through it:

  • getThreadCpuTime returns the CPU time of one thread in nanoseconds, or -1 when it cannot say (for example when the thread has ended). We treat -1 as "not on the CPU".
  • lastCpuNanos.put stores the new value and returns the old one in a single call. The first time we see a thread there is no old value, so it does not count.
  • A thread counts only when it used at least a quarter of the interval. That threshold keeps a thread that woke up for a microsecond from being counted as busy.

Run it:

java -javaagent:agent.jar=mode=cpu -cp work Workload
done true
prof: 284 samples
  thread [main]      99.6%
  thread [acceptor]   0.4%
  total   self  method
   99.6%   0.0%  Workload.main
   59.9%  59.9%  Workload.hot
   29.6%  13.0%  Workload.warm
   16.5%   0.4%  java.lang.StringBuilder.append
   16.2%   0.7%  java.lang.AbstractStringBuilder.append
    9.9%   9.9%  Workload.cold
    8.5%   8.5%  java.lang.Integer.getChars

Now main has almost every sample, and the three methods are back at their true shares. The idle threads are gone, which is correct: they use no CPU. A stray sample or two can still land on another thread that was busy for a moment, such as acceptor while it set up its socket.

Step 3.3: Wall-clock mode (about 35 minutes)

CPU mode answers "where is the processor going?". It cannot answer the other question that matters just as often: "why is this request slow?". A request that spends 90% of its time waiting for a lock uses almost no CPU, and a CPU profile will look healthy. For that we want wall-clock mode, which counts every thread in every state:

Pitfall: a CPU profile of a program that mostly waits looks healthy. If a request is slow and the CPU profile shows little, switch to wall mode before you decide there is nothing to fix.

java -javaagent:agent.jar=mode=wall -cp work Workload
done true
prof: 1410 samples
  thread [holder]    20.1%
  thread [main]      20.1%
  thread [sleeper]   20.1%
  thread [acceptor]  19.9%
  thread [waiter]    19.9%
  thread [DestroyJavaVM]   0.1%
  total   self  method
   79.9%   0.0%  java.lang.Thread.run
   79.9%   0.0%  java.lang.Thread.runWith
   40.4%   0.0%  Workload.sleep
   40.4%   0.0%  java.lang.Thread.sleep
   40.4%  40.4%  java.lang.Thread.sleep0

Every thread now takes about the same share, because every thread was alive for the whole run and we sampled all of them equally. That is exactly what wall-clock mode is for: reading the stacks of the threads that wait. [sleeper] and [holder] both end in Thread.sleep, and [acceptor] ends in the native accept call. [waiter] stops at the lambda itself: the thread is stuck on its synchronized line, which is how a thread waiting for a monitor looks in a stack trace. Together with the [holder] stack, which sleeps inside the same lock, that is the whole story of the contention.

The two modes complement each other. A short rule of thumb:

QuestionMode
Which code burns CPU? Is it worth optimizing?cpu
Why is one request or one thread slow?wall, looking at that thread only
Quick look at a program you have not seen yetcpu, then wall if CPU is low

Step 3.4: What does sampling cost? (about 30 minutes)

The sampler is not free. Each snapshot has to stop the threads long enough to read their stacks, and the more often we do it, the more we disturb the program we are measuring. Compare an interval of 1 ms with 10 ms:

done true
prof: 2054 samples
done true
prof: 278 samples

With a 10 ms sleep between snapshots we get a little under 100 samples a second, because the snapshot itself takes time. With 1 ms we get several hundred a second, but not 1000, for the same reason. More samples give a smoother picture, and each sample costs the program some of its time. Pick the interval by what the program can afford, and go lower only while you chase one specific problem.