SteelReed

Search

Search posts, questions…

ConcurrencyQuestion 8 / 19

Middle

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.

waits for lock Bwaits for lock Abreak the cycleThread 1 holds lock AThread 2 holds lock BLock in fixed orderor tryLock with timeout

3 points to say:

  1. A deadlock needs all four Coffman conditions; prevent it by breaking one: a fixed lock order or tryLock with a timeout.
  2. Detect it with a thread dump (jstack, the JVM reports "Found one Java-level deadlock") or monitor ThreadMXBean.findDeadlockedThreads().
  3. 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.