junxi
junxi

Reputation: 174

Deadlock - is this program deadlock able?

Is it possible that a deadlock occurs in this code?

I ran it multiple times and didn't have one, but the task asks for an explanation whether or not a deadlock situation is possible.

public class DeadlockTest {
  public static void main(String[] args) {
    ReentrantLock[] locks = new ReentrantLock[3]; 
    for (int i = 0; i < 3; i++) {
        locks[i] = new ReentrantLock(); 
    }
    WorkerThread[] threads = new WorkerThread[3]; 
    for (int i = 0; i < 3; i++) {
        threads[i] = new WorkerThread(locks[i], locks[(i+1)%3]);
        threads[i].start();
    }
  }
}

class WorkerThread extends Thread {
   private ReentrantLock l1;
   private ReentrantLock l2;
      public WorkerThread(ReentrantLock l1, ReentrantLock l2) {
         this.l1 = l1;
         this.l2 = l2; 
      }
   public void run() {
     l1.lock();
     l2.lock();
     System.out.println("Working now.");
     l1.unlock();
     l2.unlock();
   } 
}

Upvotes: 1

Views: 67

Answers (2)

hunter
hunter

Reputation: 4183

fge has given a crystal clear answer for your question. but still you might think that why it is not get deadlocked when you run it.

try to add

   try
    {
      Thread.sleep(10);
    }
    catch (InterruptedException e)
    {
      e.printStackTrace();
    }

just after l1.lock();

you will realize how it is possible to get deadlocked.

Upvotes: 0

fge
fge

Reputation: 121790

There is definitely a possibility of deadlock here:

  • thread 0 will try and hold locks 0 and 1, in this order;
  • thread 1 will try and hold locks 1 and 2, in this order;
  • thread 2 will try and hold locks 2 and 0, in this order.

Recall that even though in code you schedule threads to run "one after the other", the underlying scheduler may choose otherwise. Also, it is not because a thread is currently executed that all of its code is executed.

This scenario is possible:

  • thread 1 holds lock 1;
  • thread 2 holds lock 2;
  • thread 1 tries and holds lock 2: it cannot --> thread is blocked;
  • thread 0 holds lock 0;
  • thread 2 tries and holds lock 0: it cannot --> thread is blocked;
  • thread 0 tries and holds lock 1: it cannot --> thread is blocked.

Deadlock!

Upvotes: 3

Related Questions