Skip to content

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 unlock

3 Variants of 2PL ​

VariantRelease Write LocksRelease Read LocksCascading Rollback
Basic 2PLAnytime in shrinkingAnytime in shrinkingPossible
Strict 2PLOnly at COMMITAnytime in shrinkingPrevented
Rigorous 2PLOnly at COMMITOnly at COMMITPrevented

The Big Problem with 2PL — Deadlock ​

T1 holds Lock(A) → wants Lock(B)
T2 holds Lock(B) → wants Lock(A)
Both waiting forever → DEADLOCK

How 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 ​

2PLMVCC
MechanismLocksVersions
Readers block writers?YesNo
Deadlocks possible?YesRare
SerializabilityYesNeeds SSI
Used inOlder systemsModern DBs