Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does the following code result in deadlock

I have the following class

public class LockTester implements Runnable{
 private static Locker locker = new Locker();

 public static void main(String[] args){
  for(int i=0;i<10;i++){
   Thread t = new Thread(new LockTester());
   t.start();
  }
 }

 public void run(){
   for(int i=0;i<1000;i++){
    locker.unlockFirst();//note unlocking here
    locker.lockFirst();
    locker.lockSecond();
    locker.unlockSecond();
    locker.unlockFirst();
  }
 }
}

and Locker class

public class Locker{
 private Lock lock1 = new ReentrantLock();
 private Lock lock2 = new ReentrantLock();

 public void lockFirst(){
  lock1.lock();
 }
 public void lockSecond(){
  lock2.lock();
 }
 public void unlockFirst(){
  if(lock1.tryLock()){//note change
   lock1.unlock();
  }
 }
 public void unlockSecond(){
  lock2.unlock();
 }
}

Why does running this code result in deadlock.

like image 626
Raks Avatar asked Feb 11 '26 09:02

Raks


2 Answers

lock1 is locked twice: once in lockFirst and again in unlockFirst (lock1.tryLock()), but unlocked only once in unlockFirst.

ReentrantLock has a hold count. See ReentrantLock. If you call tryLock, even if it's already held by the current thread it still increments the hold count. So, you increment it twice, but only decrement it once.

like image 101
Tudor Avatar answered Feb 13 '26 08:02

Tudor


Having locked lock1, you never fully unlock it. If the thread holds lock1 when it calls unlockFirst(), it will still hold lock1 when the function returns.

If you call lock1.lock() followed by a successful lock1.tryLock(), you need to call lock1.unlock() twice to completely release the lock. Your code doesn't do that, hence the deadlock.

like image 42
NPE Avatar answered Feb 13 '26 08:02

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!