Deadlock: Cause and Prevention
40 min · Advanced
A deadlock is when two or more threads each hold a lock and wait forever for a lock another one holds, so none of them can continue. "Write code that causes a deadlock, then fix it" is a favourite interview task. Section 10, Classic Concurrency Bugs, taught it; this lesson is the revision.
Topics in this lesson
- Writing a two-lock deadlock on demand
- The four necessary conditions
- Prevention: lock ordering and tryLock with a timeout
- Detecting a deadlock with a thread dump (jstack)
- Livelock and starvation
Interview questions this lesson answers
- What is a deadlock?
- Can you write code that causes a deadlock?
- What are the four necessary conditions for a deadlock?
- How do you prevent deadlock?
- How do you order locks when the objects have no natural order?
- How does tryLock help with deadlocks?
- How do you detect a deadlock in a running application?
- How can a program detect deadlocks by itself?
- Can you recover from a deadlock on synchronized blocks?
- What is the difference between deadlock and livelock?
Sign in free to continue this lesson
Create a free account to read every lesson, practise with the exercises and keep track of your progress.