A deadlock because

The root cause of deadlock in Java is that a cross closed loop application occurs during lock application. That is, A thread applies for lock B when it has acquired lock A and has not released it. At this time, another thread has acquired lock B and needs to acquire lock A before releasing lock B. Therefore, A closed loop occurs and A deadlock cycle occurs.

Monitor the deadlock

The VisualVM monitoring tool has obvious thread deadlock alerts and can also monitor the thread, class, number of lines of code, and data type that issued the deadlock.

Analysis of the deadlock

  1. VisualVM generates Threaddump to find the memory address of the deadlocked code block

2. VisualVM generates Heapdump and uses OQL to view the deadlocked object values and references

select heap.findObject("0x00000006c0276428")
Copy the code

  1. Another way to use OQL
Jmap-dump :live,file=/data/test.map < JPS port number > Jhat /data/test.map Visit http://ip:7000/Copy the code

The sample code

/ / static class SynAddRunalbe implements Runnable {int a, b; public SynAddRunalbe(int a, int b) { this.a = a; this.b = b; } @Override public void run() { synchronized (Integer.valueOf(a)) { synchronized (Integer.valueOf(b)) { System.out.println(a + b); } } } public static void main(String[] args) throws Exception { for (int i=0; i< 100; i++) { new Thread(new SynAddRunalbe(1, 2)).start(); new Thread(new SynAddRunalbe(2, 1)).start(); }}Copy the code

Scan it. Focus on me