Deadlocks related
- details
- Live lock: a thread keeps retrying an operation that always fails, causing it to fail
- Starvation: a thread is constantly delayed by the scheduler from accessing the resource it depends on to execute. Perhaps the scheduler executes a higher-priority thread before a lower-priority thread, while there is always a higher-priority thread available to execute. Starvation is also called infinite delay
Simulate deadlocks and tool use
public class DeadLockTest {
Object lock1 = new Object();
Object lock2 = new Object();
public void method1(a){
// When a thread acquires lock1 and attempts to acquire lock2, but lock2 may have already been acquired by another thread, the thread will block
synchronized (lock1){
synchronized (lock2){
System.out.println("Thread-001 invoked"); }}try {
Thread.sleep(100);
} catch(InterruptedException e) { e.printStackTrace(); }}public void method2(a){
// When a thread has acquired lock2 and wants to acquire lock1, but lock1 may have been acquired by another thread, the thread will block
synchronized (lock2){
synchronized (lock1){
System.out.println("Thread-002 invoked"); }}try {
Thread.sleep(210);
} catch(InterruptedException e) { e.printStackTrace(); }}/* When two threads acquire lock1 and lock2 respectively and cannot release them, a deadlock will occur */
public static void main(String[] args) {
DeadLockTest deadLockTest = new DeadLockTest();
Runnable run1 = ()->{
while (true){ deadLockTest.method1(); }}; Runnable run2 = ()->{while (true){ deadLockTest.method2(); }};new Thread(run1,"Thread-001").start();
new Thread(run2,"Thread-002").start(); }}Copy the code
Use visual toolsjvisualvm
- Shell window input
jvisualvm
- This comes with the JDK
- Run the code above that may cause deadlocks
- Thread Dump
Use the command line to view
jps -l
First check the ID of the process that generated the deadlock
Jstack process id
Detection of deadlock
- The results of
- It’s actually the same as visualizing it