Java Thread Determining Cpu Time

0

In this article, we will see how to determine the CPU time used by a thread. If any thread is stuck, we can figure out which thread is consuming more cpu time.
In our example, we create multiple threads, assign task and start them. The task handled by each thread is similar, except the time of execution, which in turn is controlled using a loop count passed in from the main method as we construct the task.

Let’s now look into the thread task. In the task, we start a loop for the count passed in and do some trivial stuff within the loop.

  1. We create a string array for the size of loop count.
  2. We then start the loop, manufacture some string value and assign it to the array element.
  3. We again loop through each string element and construct a string buffer
  4. As the loop reaches half of the count, we make the thread sleep so that the main thread can catch up to calculate the cpu time.

MyTask:

package com.javarticles.threads;

public class MyTask implements Runnable{
    private String name;
    private int count;
    public MyTask(String name, int count) {
        this.name = name;
        this.count = count;
    }
    public void run() {
        String[] strArray = new String[count];
        System.out.println("Start MyTask (" + name + "), loop count " + count);
        for (int i = 0; i < count; i++) {
            strArray[i]= "String " + (i * 10);
        }
        StringBuffer sb = new StringBuffer();
        int i = 0;
        for (String str : strArray) {
            sb.append(str).append("\n");
            i++;
            if (i == count/2) {
                //sleep so that main thread can catch up to calculate the cpu times 
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }      
        System.out.println(name + " done");
    }

}

Determine Thread CPU Time

  1. We create three threads
  2. Each task is based on a loop count
  3. We make the main thread sleep so that the threads started can catch up with their task
  4. When the main thread wakes up, it will start calculating the cpu time for each thread

Here is how we determine cpu time:

    1. Get the thread MBean
      ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();
      
    2. Verify whether the JVM allows cpu time measurement for any thread.
      ThreasMXBean.isThreadCpuTimeSupported()
      
    3. Determine the total CPU time for a thread of the specified ID. The returned value is in nanoseconds.
      ThreadMXBean.getThreadCpuTime(thr.getId());
      

ThreadCpuTimeExample:

package com.javarticles.threads;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

public class ThreadCpuTimeExample {
    public static void main(String[] args) {
        Thread[] threads = new Thread[3];
        threads[0] = new Thread(new MyTask("Task1", 50000), "Thread1");
        threads[1] = new Thread(new MyTask("Task2", 600000), "Thread2");
        threads[2] = new Thread(new MyTask("Task3", 900000), "Thread3");
        threads[0].setDaemon(true);
        threads[1].setDaemon(true);
        threads[2].setDaemon(true);
        threads[0].start();
        threads[1].start();
        threads[2].start();
        //sleep so that other threads catch up
        try {
            Thread.sleep(100);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        System.out.println("Calculate Thread CPU Time");
        for (Thread thread : threads) {
            System.out.println(thread.getName() + "'s cpu time: " + cpuTime(thread));
        }
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }  
        System.out.println("All threads finished their tasks");
    }
    
    private static long cpuTime(Thread thr) {
        ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();
        if (mxBean.isThreadCpuTimeSupported()) {
            try {
                return mxBean.getThreadCpuTime(thr.getId());
            } catch (UnsupportedOperationException e) {
                System.out.println(e.toString());
            }
        } else {
            System.out.println("Not supported");
        }
        return 0;
    }
}

Output:

Start MyTask (Task1), loop count 50000
Start MyTask (Task2), loop count 600000
Start MyTask (Task3), loop count 900000
Calculate Thread CPU Time
Thread1's cpu time: 15600100
Thread2's cpu time: 31200200
Thread3's cpu time: 46800300
Task1 done
Task2 done
Task3 done
All threads finished their tasks

Download the source code

This was an example about determining cpu time consumed by a thread.

You can download the source code here: javaThreadCpuTimeExample.zip

About Author

Ram's expertise lies in test driven development and re-factoring. He is passionate about open source technologies and loves blogging on various java and open-source technologies like spring. You can reach him at rsatish.m@gmail.com

Comments are closed.