日期:2014-05-16  浏览次数:20723 次

Identify Java code consuming high CPU in Linux--linking JVM thread and Linux PID

The original article is in : http://blogs.manageengine.com/appmanager/2011/02/09/identify-java-code-consuming-high-cpu-in-linux-linking-jvm-thread-and-linux-pid/

?

We can easily identify a problematic java code which leads to high CPU utilization in Linux. Let me explain the steps with the following example,

  1. ?package test;
  2. ?public class ThreadDumpTest {
  3. ???????? public void test(){
  4. ???????????????? for (int i = 0; i < 10 ; i++) {
  5. ???????????????????????? Thread th=new Thread(new TR(i));
  6. ???????????????????????? th.setName(“MyThread-”+(1000+i));
  7. ???????????????????????? th.start();
  8. ???????????????? }
  9. ???????? }
  10. ???????? public static void main(String[] args) {
  11. ???????????????? ThreadDumpTest t=new ThreadDumpTest();
  12. ???????????????? t.test();
  13. ???????? }
  14. ???????? private class TR implements Runnable{
  15. ???????????????? int ins=0;
  16. ???????????????? TR(int i){
  17. ???????????????????????? ins=i;
  18. ???????????????? }
  19. ???????????????? public void run(){
  20. ???????????????????????? while (true) {
  21. ???????????????????????????????? if(ins!=5) {
  22. ???????????????????????????????????????? try {
  23. ???????????????????????????????????????????????? Thread.sleep(10000);
  24. ???????????????????????????????????????? } catch (Exception e) {
  25. ???????????????????????????????????????????????? e.printStackTrace();
  26. ???????????????????????????????????????? }
  27. ???????????????????????????????? }
  28. ???????????????????????? }
  29. ???????????????? }
  30. ???????? }
  31. ?}

In the above example, all the threads are in while loop. Except ‘MyThread-1005 ‘ thread, all other threads will sleep 10 secs inside the loop. The ‘MyThread-1005 ‘ thread will not enter sleep part, so it will run in while loop without sleep. Due to while loop, the ‘MyThread-1005 ‘ thread will leads to high CPU utilization.

How to identify ?

Step 1 :

Execute ‘top ‘ command on the console. You can see the ‘java’ command with PID 7074 utilized 97% of CPU.

Step 2 :

The top command displays the process list like the above image. Press ‘Shift + h ‘ and wait few secs. You can see ‘Show threads on ‘ message in the top console. Now, you can see thread level details like CPU/Memory utilization. You can see a ‘java’ command thread with PID 7087 utilized 94% of CPU.

Step 3:

The identified problematic thread PID ( 7087 ) is in decimal format. Convert it into hexadecimal format . The respective hexadecimal for 7087 is 1BAF. And convert it into lowercase (1baf ).

Step 4:

?

Take thread dump and search the converted hexadecimal PID ( 1baf ) in the thread dump. You can find the hex PID as ‘