What is a deadlock, and how do you detect and prevent it? How do livelock and starvation differ?
Short answer
A deadlock is threads waiting on each other in a cycle: each holds a lock the other needs. Prevent it by acquiring locks in a fixed order or with tryLock and a timeout; detect it with a thread dump.
3 points to say:
- A deadlock needs all four Coffman conditions; prevent it by breaking one: a fixed lock order or
tryLockwith a timeout. - Detect it with a thread dump (
jstack, the JVM reports "Found one Java-level deadlock") or monitorThreadMXBean.findDeadlockedThreads(). - Livelock: threads keep running but make no progress (fix with random backoff); starvation: one thread never gets its turn (use a fair lock).
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.