Appearance
Two-Phase Locking (2PL)
A concurrency control protocol that guarantees serializability using locks.
Core Idea: A transaction must acquire ALL locks before releasing ANY lock.
The Two Phases
Phase 1 — Growing Phase
Transaction can ONLY acquire locks. Cannot release any lock yet.
Phase 2 — Shrinking Phase
Transaction can ONLY release locks. Cannot acquire any new lock.
-- GROWING PHASE
T1: Lock(A) T1: Lock(B) T1: Read(A) T1: Write(B)
-- LOCK POINT (peak — no more acquisitions after this)
-- SHRINKING PHASE
T1: Unlock(A) T1: Unlock(B)
-- T1 cannot acquire any new lock after first unlock3 Variants of 2PL
| Variant | Release Write Locks | Release Read Locks | Cascading Rollback |
|---|---|---|---|
| Basic 2PL | Anytime in shrinking | Anytime in shrinking | Possible |
| Strict 2PL | Only at COMMIT | Anytime in shrinking | Prevented |
| Rigorous 2PL | Only at COMMIT | Only at COMMIT | Prevented |
The Big Problem with 2PL — Deadlock
T1 holds Lock(A) → wants Lock(B)
T2 holds Lock(B) → wants Lock(A)
Both waiting forever → DEADLOCKHow DBs handle deadlocks
- Deadlock Detection → Build a wait-for graph; if cycle detected → abort one transaction
- Deadlock Prevention → Assign priorities by timestamp; younger transaction always aborts (wound-wait)
- Timeout → If waiting too long → assume deadlock → abort
2PL vs MVCC
| 2PL | MVCC | |
|---|---|---|
| Mechanism | Locks | Versions |
| Readers block writers? | Yes | No |
| Deadlocks possible? | Yes | Rare |
| Serializability | Yes | Needs SSI |
| Used in | Older systems | Modern DBs |