Which Java thread is hogging the CPU?

前端 未结 12 1715
萌比男神i
萌比男神i 2020-12-07 07:48

Let\'s say your Java program is taking 100% CPU. It has 50 threads. You need to find which thread is guilty. I have not found a tool that can help. Currently I use the follo

12条回答
  •  太阳男子
    2020-12-07 08:38

    Use ps -eL or top -H -p , or if you need to see and monitor in real time, run top (then shift H), to get the Light Weight Process ( LWP aka threads) associated with the java process.

    root@xxx:/# ps -eL
    PID LWP TTY TIME CMD
     1 1 ? 00:00:00 java
     1 7 ? 00:00:01 java
     1 8 ? 00:07:52 java
     1 9 ? 00:07:52 java
     1 10 ? 00:07:51 java
     1 11 ? 00:07:52 java
     1 12 ? 00:07:52 java
     1 13 ? 00:07:51 java
     1 14 ? 00:07:51 java
     1 15 ? 00:07:53 java
    …
     1 164 ? 00:00:02 java
     1 166 ? 00:00:02 java
     1 169 ? 00:00:02 java
    

    Note LWP= Lightweight Process; In Linux, a thread is associated with a process so that it can be managed in the kernel; LWP shares files and other resources with the parent process. Now let us see the threads that are taking most time

     1 8 ? 00:07:52 java
     1 9 ? 00:07:52 java
     1 10 ? 00:07:51 java
     1 11 ? 00:07:52 java
     1 12 ? 00:07:52 java
     1 13 ? 00:07:51 java
     1 14 ? 00:07:51 java
     1 15 ? 00:07:53 java
    

    Jstack is a JDK utility to print Java Stack; It prints thread of the form.

    Familiarize yourself with others cool JDK tools as well (jcmd jstat jhat jmap jstack etc — https://docs.oracle.com/javase/8/docs/technotes/tools/unix/)

    jstack -l

    The nid, Native thread id in the stack trace is the one that is connected to LWT in linux (https://gist.github.com/rednaxelafx/843622)

    “GC task thread#0 (ParallelGC)” os_prio=0 tid=0x00007fc21801f000 nid=0x8 runnable
    

    The nid is given in Hex; So we convert the thread id taking the most time 8,9,10,11,12,13,14,15 in DEC = 8,9,A, B,C,D,E,F in HEX.

    (note that this particular stack was taken from Java in a Docker container, with a convenient process if of 1 ) Let us see the thread with this ids..

    “GC task thread#0 (ParallelGC)” os_prio=0 tid=0x00007fc21801f000 nid=0x8 runnable
    “GC task thread#1 (ParallelGC)” os_prio=0 tid=0x00007fc218020800 nid=0x9 runnable
    “GC task thread#2 (ParallelGC)” os_prio=0 tid=0x00007fc218022800 nid=0xa runnable
    “GC task thread#3 (ParallelGC)” os_prio=0 tid=0x00007fc218024000 nid=0xb runnable
    “GC task thread#4 (ParallelGC)” os_prio=0 tid=0x00007fc218026000 nid=0xc runnable
    “GC task thread#5 (ParallelGC)” os_prio=0 tid=0x00007fc218027800 nid=0xd runnable
    “GC task thread#6 (ParallelGC)” os_prio=0 tid=0x00007fc218029800 nid=0xe runnable
    “GC task thread#7 (ParallelGC)” os_prio=0 tid=0x00007fc21802b000 nid=0xf runnable
    

    All GC related threads; No wonder it was taking lot of CPU time; But then is GC a problem here.

    Use jstat (not jstack !) utility to have a quick check for GC.

    jstat -gcutil

提交回复
热议问题