Two-Phase Locking (2PL)

Two-Phase Locking is a concurrency control protocol that guarantees serializability — the gold standard of isolation. It is the most widely used concurrency control mechanism in DBMS implementations. The protocol divides each transaction’s lifetime into two distinct phases.

The Two Phases

Growing Phase

The transaction acquires locks but does not release any. It can request new shared or exclusive locks as needed.

Shrinking Phase

The transaction releases locks but does not acquire any new ones. Once the first lock is released, no more locks can be obtained.

graph LR
    subgraph Growing Phase
        A[Acquire Locks] --> B[No Releases]
    end
    subgraph Lock Point
        C((Maximum Locks Held))
    end
    subgraph Shrinking Phase
        D[Release Locks] --> E[No Acquires]
    end
    B --> C --> D

Lock Types

LockSymbolAllows concurrent
Shared (S-lock)SOther S-locks (reads)
Exclusive (X-lock)XNothing (blocks all)

Lock Compatibility Matrix

SX
SYesNo
XNoNo

Variants

Basic 2PL

Locks can be released during the transaction after the lock point. Can lead to cascading aborts — if transaction T₁ releases a lock and T₂ reads the unlocked data, then T₁ aborts, T₂ must also abort.

Strict 2PL

All exclusive (write) locks are held until the transaction commits or aborts. Prevents cascading aborts and is the most common implementation.

Rigorous 2PL

All locks (shared and exclusive) are held until commit/abort. Simplifies reasoning — transactions appear to execute in commit order.

Conservative 2PL

All locks are acquired before the transaction begins. Prevents deadlocks entirely but requires knowing the full read/write set in advance (impractical for most workloads).

Lock Manager Internals

The lock manager is a specialized DBMS component that processes all lock/unlock requests:

  • Maintains a lock table — a hash table indexed by data item identifier, pointing to linked lists of lock records
  • Each record contains: Transaction ID, Lock Mode (S or X), Request Status (granted or pending)
  • Responds with either a Lock Grant or a Rollback Message (if deadlock detected)
  • Lock/unlock operations are atomic — enforced via semaphores to prevent race conditions

Anti-Starvation

If T₁ holds an S-lock on Q and T₂ requests an X-lock (must wait), then T₃ arrives requesting an S-lock (compatible with T₁’s S-lock) — the lock manager queues T₃ behind T₂ rather than granting it immediately. This prevents T₂ from starving indefinitely behind a stream of readers.

Deadlocks

2PL is susceptible to deadlocks — two or more transactions each waiting for a lock held by the other.

Detection: Wait-for graph — if a cycle exists, a deadlock has occurred. The DBMS selects a victim transaction to abort (typically the youngest or cheapest).

Prevention (timestamp-based):

  • Wait-Die — Older transactions wait; younger ones abort and retry
  • Wound-Wait — Older transactions force younger ones to abort; younger ones wait

Sources