Java Thread Series (7) Deadlock

Java Thread Series (7) Deadlock

Deadlocks can occur when threads need to hold multiple locks at the same time. Consider the following situation:

Thread A currently holds mutex lock1, and thread B currently holds mutex lock2. Next, while thread A is still holding lock1, it tries to acquire lock2, because thread B is holding lock2, so thread A blocks waiting for thread B to release lock2. If thread B is also trying to acquire lock1 while holding lock2 at this time, because thread A is holding lock1, thread B will block waiting for A to release lock1. Both are waiting for the lock held by the other party to be released, but neither of them has released the lock held by themselves. At this time, the two will continue to block. This situation is called deadlock.

An example of a deadlock between two threads is given below, as follows:

/**
 * 多个线程挣抢同一份资源,容易造成死锁
 * @author: leigang
 * @version: 2018-05-05
 */
public class DeadThread {

    public static void main(String[] args) {
        Object goods = new Object();
        Object money = new Object();

        new Test1(goods, money).start();
        new Test2(goods, money).start();

    }

    static class Test1 extends Thread {
        private Object goods;
        private Object money;

        public Test1(Object goods, Object money) {
            this.goods = goods;
            this.money = money;
        }

        @Override
        public void run() {
            while (true) {
                test();
            }
        }

        public void test() {
            synchronized (goods) {  // (1)
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (money) {
                }
            }
            System.out.println(Thread.currentThread().getName() + "先交货再给钱");
        }
    }

    static class Test2 extends Thread {
        private Object goods;
        private Object money;

        public Test2(Object goods, Object money) {
            this.goods = goods;
            this.money = money;
        }

        @Override
        public void run() {
            while (true) {
                test();
            }
        }

        public void test() {
            synchronized (money) {  // (2)
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (goods) {
                }
            }
            System.out.println(Thread.currentThread().getName() + "先给钱再交货");
        }
    }
}

Description: Thread 1 holds the goods lock and intends to acquire the money lock, but thread 2 already holds the money lock and intends to acquire the goods lock. Since both locks are locked, neither thread can acquire the corresponding lock. This creates a deadlock.

Most code is not prone to deadlocks. Deadlocks can be hidden in the code for a long time, waiting for an uncommon condition to occur, but even a small probability, once it occurs, it can cause devastating damage. Avoiding deadlocks is difficult, and following these principles can help avoid deadlocks:

1. Hold the lock only for the shortest time necessary, and consider using a synchronized statement block instead of the entire synchronization method;

2. Try to write code that does not need to hold multiple locks at the same time. If it is unavoidable, ensure that the thread holds the second lock for as short a time as possible;

3. Create and use a large lock instead of several small locks, and use this lock for mutual exclusion rather than as an object-level lock for a single object;

Since multiple threads operating the same object are prone to deadlock, how to solve this problem? A classic solution is the producer -consumer pattern

refer to:

"Java Concurrent Programming": http://www.importnew.com/20638.html


Record a little bit every day. Content may not be important, but habits are!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325366726&siteId=291194637