Interview question: to realize a deadlock (Java version), the four necessary conditions for deadlock generation, how to avoid deadlock and how to solve deadlock

Posted by Gen-ik on Sat, 26 Feb 2022 03:32:53 +0100

Implement the simplest deadlock (Java version)

```java
/**
 * @author wall
 * @date 2019/7/29  16:42
 * @description Implement A deadlock: thread A obtains the lock held by thread B, and thread B obtains the lock held by thread A
 */
public class DeadLock {
    //Define two locks
    private static ReentrantLock lockA = new ReentrantLock();
    private static ReentrantLock lockB = new ReentrantLock();
    //test
    public static void main(String[] args) {
        //Start thread A,B
        new Thread(new A()).start();
        new Thread(new B()).start();
    }
 
    static class A implements Runnable{
        @Override
        public void run() {
            Thread.currentThread().setName("A thread ");
            //Acquire lock A
            lockA.lock();
            System.out.println(Thread.currentThread().getName()+"Acquire lock A");
            //Simulate business operation
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //Obtain lock B again
            lockB.lock();
            System.out.println(Thread.currentThread().getName()+"Acquire lock B");
            lockA.unlock();
            lockB.unlock();
        }
    }
 
    static class B implements Runnable{
        @Override
        public void run() {
            Thread.currentThread().setName("B thread ");
            //Acquire lock B
            lockB.lock();
            System.out.println(Thread.currentThread().getName()+"Acquire lock B");
            //Simulate business operation
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //Obtain lock A again
            lockA.lock();
            System.out.println(Thread.currentThread().getName()+"Acquire lock A");
        }
    }
}

Four necessary conditions for deadlock
① Resources are mutually exclusive / resources are not shared

Mutually exclusive condition: a resource can only be used by one process at a time.

② Possession and waiting / request and hold

(request and hold condition: when a process is blocked by requesting resources, it will hold on to the obtained resources.

③ Resources are inalienable

The resources obtained by the process cannot be forcibly deprived until they are used up.

④ Loop waiting

A circular waiting resource relationship is formed between several processes.

For example ▼

Xiaoming has a keyboard and Xiaobai has a mouse. Xiaoming wants to play games with a computer. Xiaobai wants to use a computer to do PPT. Xiaoming can't play games without a mouse. Xiaobai can't do PPT without a keyboard. Xiaoming and other Xiaobai give the mouse to themselves, and Xiaobai also waits for Xiaoming to give the keyboard to himself, but Xiaoming doesn't want to give the keyboard to Xiaobai, and Xiaobai doesn't want to give the mouse to Xiaoming, Xiaoming and Xiaobai can't grab the keyboard and mouse from each other, so they form a deadlock.

Ways to avoid deadlock

1. Banker algorithm
2. Avoid multiple locks. Try to avoid locking multiple locks by the same thread. For example, in the above deadlock program, the main thread needs to Lock the locks of objects A and B, and the secondary thread also needs to Lock the locks of objects A and B, which buries the hidden danger of deadlock.
Have the same locking sequence. (add order to locks) if multiple threads need to Lock multiple locks, they should ensure that they request locks in the same order. For example, in the deadlock program above, the main thread first locks the Lock of object A, and then locks the Lock of object B; The secondary thread locks the Lock of object B first, and then locks the Lock of object A. This locking sequence is easy to form nested locking, which leads to deadlock. If the main thread and the secondary thread are locked in the same order, this problem can be avoided.
3. Use timing Lock. When calling the acquire() method to Lock, the program can specify the timeout parameter, which specifies that the Lock will be automatically released after timeout seconds, so that the deadlock can be unlocked.
4. Deadlock detection. Deadlock detection is a deadlock prevention mechanism based on algorithm mechanism. It is mainly aimed at those scenes where it is impossible to realize sequential locking and timed locking.

Deadlock Relieving
1. Resource deprivation law

Suspend some deadlock processes, preempt its resources, and allocate these resources to other deadlock processes. However, the suspended process should be prevented from being in a state of lack of resources for a long time.

2. Revocation process law

Forcibly undo some or even all deadlock processes and deprive them of resources. The revocation principle can be carried out according to the process priority and the cost of revoking the process.

3. Process fallback method

Allow one (more) processes to fall back enough to avoid deadlock, and voluntarily release resources instead of being deprived when processes fall back. The system is required to keep the historical information of the process and set the restore point.
--------
Copyright notice: This is the original article of CSDN blogger "virtual soil", which follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this notice for reprint.
Original link: https://blog.csdn.net/weixin_42228338/article/details/97686461

Topics: Java JavaSE