Is it possible to deadlock with two locks and just one method that acquires both locks while all other methods acquire just one?

StackOverflow https://stackoverflow.com/questions/21943269

Do I run the risk of deadlocking with the code below? Is there a better/safer way of doing this? Initially I thought about combining somehow two locks into one, but maybe I am pushing too hard here and the code below is safe and correct.

public void method1() {

    lock1.lock();
    //...
    lock1.unlock();
}

public void method2() {
   lock2.lock();
   //...
   lock2.unlock();
}

public void method3() {
   lock1.lock();
   lock2.lock();
   // ...
   lock2.unlock();
   lock1.unlock();
}
有帮助吗?

解决方案

In this scenario, method3 can't have lock2 locked without lock1 locked, so a deadlock cannot happen in that method. Note that this doesn't prevent some kind of additional code not shown to acquire lock2 before lock1, such as

public void method4() {
   lock2.lock();
   lock1.lock();
   // ...
   lock1.unlock();
   lock2.unlock();
}

This, when run concurrently with method3 can produce a deadlock.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top