Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ThreadMXBean.getThreadCpuTime() include time spent in all states, or just RUNNABLE?

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...

like image 807
Markus Jevring Avatar asked Jun 08 '12 07:06

Markus Jevring


3 Answers

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();
            }
        }
    }
like image 77
petithug Avatar answered Nov 01 '22 09:11

petithug


Yes, this is only RUNNABLE, you can receive further statistics of time spent in other states through ThreadInfo with the following methods:

  • getBlockedTime()
  • getWaitedTime()

There is no further discrimination between TIMED_WAITING and WAITING in getWaitedTime().

like image 45
Konrad Reiche Avatar answered Nov 01 '22 10:11

Konrad Reiche


Runnable only. That's it, otherwise it'd be useless.

like image 1
bestsss Avatar answered Nov 01 '22 11:11

bestsss