How Relational Databases Prevent Data Corruption: Two-Phase Locking (2PL)
When hundreds of database transactions read and write to the same tables concurrently, simply using locks is not enough.
If transactions acquire and release locks haphazardly, the database can produce non-serializable anomalies βsuch as reading partial updates, lost updates, or inconsistent snapshots.
To mathematically guarantee Conflict Serializability , relational database engines enforce Two-Phase Locking (2PL) .
β‘ The Two Phases of 2PL
A transaction must divide its lock operations into two distinct, non-overlapping phases:
Locks Held β² β [ Lock Point ] β /\ β / \ β GROWING / \ SHRINKING β PHASE / \ PHASE β (Acquire) / \ (Release) β / \ βββββββββββββ/ββββββββββββ\ββββββββββββββΊ Time
Enter fullscreen mode
Exit fullscreen mode
Growing Phase :
The transaction may acquire new locks (Shared or Exclusive).
The transaction CANNOT release any locks .
The Lock Point :
The exact moment the transaction acquires its final lock.β¦