How to see the cpu usage percentage of each thread of a java process


Well, I have a problem with cpu usage, and I don't know exactly which class or Thread it's consuming (there's no way to know externally from the code), I was wondering if there is any method that shows all active threads with their respective usage of CPU. I tried to use a code to see the active threads, but I'm not able to see the % of CPU, is there a way to do that?

      ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();

            for(Long threadID : threadMXBean.getAllThreadIds()) {
                ThreadInfo info = threadMXBean.getThreadInfo(threadID);
                System.out.println("Nome da thread: " + info.getThreadName());
                System.out.println("Estado da thread: " + info.getThreadState());
                long cpusage = threadMXBean.getThreadCpuTime(threadID);
                System.out.println(String.format("Tempo usando a cpu: %.2f s",cpusage==0?0d:cpusage/100000000d));

I'm running the program in docker on AWS, I don't have terminal access, I need to know the information through the code, (or some other way to see this information)


You can use this to run Linux commands. You will probably be able to get the information with some linux command

Process p = Runtime.getRuntime().exec("ls -aF");
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = br.readLine()) != null)
    System.out.println("line: " + s);
System.out.println ("exit: " + p.exitValue());

See here:

Scroll to Top