How can I Monitor cpu usage per thread of a java application in a linux multiprocessor environment?

杀马特。学长 韩版系。学妹 提交于 2019-12-06 15:42:17

If you don't want to use OS specific functions like traversing the /proc directory, you can usually get the values you're looking for from the Java management interface with ThreadMXBean.getThreadCpuTime() and ThreadMXBean.getThreadUserTime().

You can infer from stat files in /proc/PID/ and /proc/PID/task/PID/. Problem is that lots of threads are generally created (maybe not with your app?) and those task files will come and go. The parent PID should however should report the user/kernel times in total scheduled time on all procs and thus compared against wallclock should give you a good start.

As jarnbjo answered, you can query the Thread management JMX Bean for the thread's cpu and user time:

import static org.junit.Assert.assertTrue;

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

import org.junit.Test;

public class ThreadStatsTest {

    @Test
    public void testThreadStats() throws Exception {
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        assertTrue(threadMXBean.isThreadCpuTimeSupported());
        assertTrue(threadMXBean.isCurrentThreadCpuTimeSupported());

        threadMXBean.setThreadContentionMonitoringEnabled(true);
        threadMXBean.setThreadCpuTimeEnabled(true);
        assertTrue(threadMXBean.isThreadCpuTimeEnabled());

        ThreadInfo[] threadInfo = threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds());
        for (ThreadInfo threadInfo2 : threadInfo) {
            long blockedTime = threadInfo2.getBlockedTime();
            long waitedTime = threadInfo2.getWaitedTime();
            long cpuTime = threadMXBean.getThreadCpuTime(threadInfo2.getThreadId());
            long userTime = threadMXBean.getThreadUserTime(threadInfo2.getThreadId());

            String msg = String.format(
                    "%s: %d ns cpu time, %d ns user time, blocked for %d ms, waited %d ms",
                    threadInfo2.getThreadName(), cpuTime, userTime, blockedTime, waitedTime);
            System.out.println(msg);
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!