What causes a deadlock in Java, and what are the four conditions that must all hold for one to happen?
A deadlock is when two or more threads each wait for something that the others are holding, so none of them can ever continue.
There are four conditions that all have to hold at the same time, and they are known as the Coffman conditions.
The first one is mutual exclusion. The resource that is being fought over can only be held by one thread at a time. A lock gives you that.
The second one is hold and wait. A thread holds on to one resource while it waits for another one.
The third one is no preemption. The resource cannot be taken away from the thread that holds it. Only the thread itself can let go.
The fourth one is circular wait. The threads form a circle, so that every one of them is waiting for the one before it.
public class Main {
public static void main(String[] args) throws InterruptedException {
Object lockA = new Object();
Object lockB = new Object();
Thread first = new Thread(new Runnable() {
public void run() {
synchronized (lockA) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
synchronized (lockB) {
System.out.println("the first thread finished");
}
}
}
});
Thread second = new Thread(new Runnable() {
public void run() {
synchronized (lockB) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
synchronized (lockA) {
System.out.println("the second thread finished");
}
}
}
});
first.start();
second.start();
// Both threads are now stuck, and neither of them will ever
// finish. This join never returns.
first.join();
second.join();
}
}
So the answer to the question is this. The four conditions are mutual exclusion, hold and wait, no preemption and circular wait. If you can show that one of them does not hold, then a deadlock is impossible.
That is what makes the conditions useful in practice. The third one is the hardest to break, because you cannot take a lock away from a thread that has it. The fourth one is the easiest, because you can always arrange for every thread to take its locks in the same order.
The next question in this topic looks at how to find a deadlock and how to stop one happening.