Reputation: 174
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
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
Reputation: 121790
There is definitely a possibility of deadlock here:
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:
Deadlock!
Upvotes: 3