1. Conditions under which deadlocks occur

  • Mutually exclusive: Only one process can use one resource at a time. Other processes cannot access resources that have been allocated to other processes.
  • Non-preemption: Cannot preempt resources already occupied by a process
  • Request and hold: A process continues to hold an allocated resource while waiting for another process to release it
  • Circular waiting: There is a closed chain of processes, so that each process occupies at least one resource required by the next process in the chain.

PS: The first three conditions are only necessary for the existence of deadlocks, but not sufficient. The fourth condition is sufficient. The same applies to threads.

2, simulate the generation of deadlock in multi-threaded environment

/** * Four conditions for deadlock: Mutex request and keep the non-preemption loop waiting for * synchronized to lock the object resource, ensuring that mutex and non-preemption * hold a resource first, Public class DeadLock {// Set two resources public static Object lock1 = new Object(); public static Object lock2 = new Object(); Public static void getLock1First(){synchronized (lock1){system.out.println ("getlock1"); getLock2(); } } public static void getLock2(){ synchronized (lock2) { System.out.println("lock1->lock2"); }} public static void getlock2First(){synchronized (lock2){system.out.println ("getlock2"); getLock1(); } } public static void getLock1(){ synchronized (lock1){ System.out.println("lock2->lock1"); }} public static void main(String[] args) {new Thread(){@override public void run() While (true){getLock1First(); while (true){getLock1First(); } } }.start(); new Thread(){ @Override public void run() { while (true){ getlock2First(); } } }.start(); }}Copy the code

3, deadlock investigation

  • Go to the bin directory of the JDK installation, start the CLI, and run the JPS command to check the ID of the running thread

  • Run the jstack -l thread ID command

  • You can see that Thread-1 and Thread-2 are waiting for each other’s monitor locks to be released.