What are the four conditions for deadlock and how can you prevent it?
A deadlock is a situation where two or more threads are permanently blocked, each waiting for a resource held by another thread in the group. No thread can proceed because each is waiting for a resource that will never be released. For a deadlock to occur, all four of the Coffman conditions must hold simultaneously.
The first condition is mutual exclusion. At least one resource must be held in a non-sharable mode — only one thread can use it at a time.
The second condition is hold and wait. A thread must be holding at least one resource while waiting to acquire additional resources held by other threads.
The third condition is no preemption. Resources cannot be forcibly taken away from a thread. A resource can only be released voluntarily by the thread holding it.
The fourth condition is circular wait. There must exist a circular chain of threads, where each thread holds a resource that the next thread in the chain is waiting for.
All four conditions must hold simultaneously. If you can break even one, deadlock becomes impossible.
The most practical prevention strategy is breaking the circular wait condition by imposing a total ordering on resource acquisition. Assign every lock a numeric priority and require that all threads acquire locks in increasing order. If Thread A holds Lock 1 and needs Lock 2, it can acquire it. But if it holds Lock 2 and needs Lock 1, the ordering rule prevents it from requesting Lock 1 without first releasing Lock 2. This eliminates cycles in the wait graph.
To break hold and wait, you can require threads to request all needed resources atomically before beginning execution. If any resource is unavailable, the thread releases everything and retries.
To break no preemption, you can allow the system to forcibly revoke resources. If a thread cannot acquire a needed resource, it releases all currently held resources and retries later.
Beyond prevention, there is deadlock detection and recovery. Systems like databases often use a wait-for graph and periodically check for cycles. When a cycle is found, one transaction is aborted (the victim) to break the deadlock.
Candidate names all four conditions but gives only superficial definitions and does not clearly explain that all four must hold simultaneously.
Candidate names and clearly explains all four Coffman conditions, explicitly states they must all hold simultaneously, and provides at least one well-detailed prevention strategy (e.g., lock ordering) with enough specificity to implement it.
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment