What is a deadlock in DBMS, and how is it detected and prevented?
MediumConceptConcurrency Control & Locking
Answer
A deadlock occurs when two or more transactions each wait for a lock held by another, so none of them can proceed.
- Detection: the DBMS keeps a wait-for graph with an edge Ti → Tj when Ti waits for a lock held by Tj. A cycle means deadlock, so the DBMS aborts one transaction (the victim) and rolls it back. MySQL InnoDB, PostgreSQL and SQL Server all work this way.
- Prevention with timestamps (an older transaction has a smaller timestamp): in wait-die, an older transaction waits for a younger one, but a younger requester dies (is rolled back). In wound-wait, an older requester wounds (aborts) the younger holder, while a younger requester waits.
- Simple measures: lock timeouts, and acquiring locks in a fixed order, such as ascending row ID.
Example:
T1: lock-X(A) ... requests B -> waits for T2
T2: lock-X(B) ... requests A -> waits for T1
The wait-for graph has the cycle T1 → T2 → T1, so the DBMS rolls back one transaction and the other continues.