JVM性能调优之排查死锁

查看死锁的步骤如下:

  1. 通过jps命令,查看java进程的PID
  2. 通过jstck PID查看线程日志
  3. 如果存在死锁,日志中会给出Found one Java-level deadlock:,定位到这个信息就可以快速定位问题。
Found one Java-level deadlock:
=============================
"Thread-1":
  waiting to lock monitor 0x000000001d1b0d58 (object 0x000000076b6cb368, a java.lang.Object),
  which is held by "Thread-0"
"Thread-0":
  waiting to lock monitor 0x000000001d1b35e8 (object 0x000000076b6cb378, a java.lang.Object),
  which is held by "Thread-1"

Java stack information for the threads listed above:
===================================================
"Thread-1":
        at com.gupaoedu.interceptor.ThreadDemo$BlockThread.run(ThreadDemo.java:38)
        - waiting to lock <0x000000076b6cb368> (a java.lang.Object)
        - locked <0x000000076b6cb378> (a java.lang.Object)
"Thread-0":
        at com.gupaoedu.interceptor.ThreadDemo$BlockThread.run(ThreadDemo.java:38)
        - waiting to lock <0x000000076b6cb378> (a java.lang.Object)
        - locked <0x000000076b6cb368> (a java.lang.Object)

Found 1 deadlock.
public class ThreadDemo {
     

    public static void main(String[] args) throws InterruptedException {
     
        Object o = new Object();
        Object o2 = new Object();
        Thread thread1 = new BlockThread(o,o2);
        Thread thread2 = new BlockThread(o2,o);
        thread1.start();
        thread2.start();
    }
    public static class BlockThread extends Thread {
     
        private final Object obj1;
        private final Object obj2;

        public BlockThread(Object obj1, Object obj2) {
     
            this.obj1 = obj1;
            this.obj2 = obj2;
        }
        @Override
        public void run() {
     
            synchronized(obj1) {
     
                try {
     
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
     
                    e.printStackTrace();
                }
                synchronized(obj2) {
     
                    System.out.println("Helo");
                }
            }
        }
    }
}

你可能感兴趣的:(JVM)