Senior
What is a deadlock? How to avoid it?
sobes.tech AI
Answer from AI
Deadlock (mutual blocking) is a situation in a multithreaded or multiprocess application where two or more threads permanently block each other, waiting for resources held by each other.
Example: Thread A has acquired resource 1 and is waiting for resource 2, while Thread B has acquired resource 2 and is waiting for resource 1 — neither can continue working.
How to avoid deadlock:
- Avoid nested locks: minimize the number of resources acquired simultaneously.
- Order resource acquisition: always acquire resources in the same order in all threads.
- Use timeouts: when attempting to acquire a lock with a timeout, you can abandon and retry later.
- Use higher-level synchronization constructs: for example,
java.util.concurrentpackages that provide safe primitives. - Avoid holding locks when calling external methods: to prevent creating chains of waiting.
In Java, you can use tryLock with a timeout:
if (lock1.tryLock(1000, TimeUnit.MILLISECONDS)) {
try {
if (lock2.tryLock(1000, TimeUnit.MILLISECONDS)) {
try {
// critical section
} finally {
lock2.unlock();
}
}
} finally {
lock1.unlock();
}
}
Thus, deadlock is a classic problem of concurrent programming, and preventing it requires discipline in managing resources and locks.