Like the topic says, does it include time spent in BLOCKED and WAITING etc, states as well, or is this just RUNNABLE? The docs just say "cpu time", which is a bit vague...
ThreadMXBean.getThreadCpuTime() includes only the time spent in the RUNNABLE state, but note that the way this is calculated depends on the platform.
Here's a program that shows that getThreadCpuTime() covers only the time the thread is actually doing something:
import java.lang.management.*;
public class Test implements Runnable {
    public static void main(String[] args)
        throws Exception {
        long time = System.nanoTime();
        Test test = new Test();
        synchronized (test) {
            new Thread(test).start();
            while (test.cpu == -1) {
                test.wait();
                }
            }
        System.out.println("time: " + (System.nanoTime() - time));
        System.out.println("cpu: " + test.cpu);
        }
    private long cpu = -1;
    public synchronized void run() {
        try {
            ThreadMXBean thread = ManagementFactory.getThreadMXBean();
            long cpu = thread.getCurrentThreadCpuTime();
            Thread.sleep(300);
            long time = System.nanoTime();
            while (System.nanoTime() - time < 700000000);
            this.cpu = thread.getCurrentThreadCpuTime() - cpu;
            }
        catch (InterruptedException _) {}
        finally {
            notify();
            }
        }
    }
Yes, this is only RUNNABLE, you can receive further statistics of time spent in other states through ThreadInfo with the following methods:
There is no further discrimination between TIMED_WAITING and WAITING in getWaitedTime().
Runnable only. That's it, otherwise it'd be useless.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With