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

Asked

Viewed 196 times

3

Well, I have a cpu usage problem, and I don’t know exactly which class or Thread you are consuming ( there’s no way to know externally the code ), I was wondering if you have any method that shows all the active threads with your respective CPU usage. I tried to use a code to see the active threads, but I can’t see the % of the CPU, has how to do it?

      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 am running the program on Docker in AWS, I do not have access to the terminal, I need to know the information through the code, ( or some other way to view this information )

  • Is it on UNIX/Linux? I won’t remember now but it has how to see the information of threads with commands like top -H. Do a search.

  • inside the jdk folder has Jconsole too, you can have an overview

  • 1

    I don’t have access to the external console, I needed that information inside the code

1 answer

-1

You can use this to run Linux commands. You can probably 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);
p.waitFor();
System.out.println ("exit: " + p.exitValue());
p.destroy();

See here: https://stackoverflow.com/questions/3403226/how-to-run-linux-commands-in-java

Browser other questions tagged

You are not signed in. Login or sign up in order to post.