← 🔀 Transactions & Concurrency Control
Subtopic 5 of 7

6.5Two-phase locking and deadlock

The idea

Two-phase locking (2PL) makes every transaction acquire all its locks before releasing any. It guarantees conflict serializability but can deadlock.

Think of it like this: Picking up all your tools before starting work and only putting them down at the end.

Why it exists

You answer true/false questions about 2PL, strict 2PL and deadlock.

How it works

  1. Shared locks coexist; an exclusive lock conflicts with everything.
  2. Growing phase: only lock requests. Shrinking phase: only unlocks. No lock after the first unlock.
  3. The lock point gives the serial order.
  4. Strict 2PL holds exclusive locks until commit. Deadlock = a cycle in the wait-for graph.

Worked example: T1: X(A) then X(B); T2: X(B) then X(A).

T1 holds A and waits for B; T2 holds B and waits for A: deadlock, even though both are two-phase.

Now play with it

  • →Run the deadlock example and read the wait-for edges.
  • →Run the non-two-phase example and read the warning.
T1 program
X(A) X(B) U(A) U(B)
S = shared lock, X = exclusive lock, U = unlock
T2 program
X(B) X(A) U(B) U(A)
S = shared lock, X = exclusive lock, U = unlock
  • T1 gets X(A)
  • T2 gets X(B)
  • T1 waits for X(B), held by T2
  • T2 waits for X(A), held by T1
  • T1 waits for X(B), held by T2
  • T2 waits for X(A), held by T1
  • T1 waits for X(B), held by T2
  • T2 waits for X(A), held by T1
  • T1 waits for X(B), held by T2
  • T2 waits for X(A), held by T1
OutcomeDeadlock: transactions wait for each other in a cycle
Wait-for edgesT1 → T2, T2 → T1
Two-phase?Yes, no lock after an unlock

2PL guarantees conflict serializability (the serial order is the order of lock points) but not freedom from deadlock. Strict 2PL holds exclusive locks until commit, which also gives strict (cascadeless) schedules.

Check yourself

Which of these does basic 2PL NOT guarantee?

Remember: 2PL: serializable but not deadlock free; strict 2PL holds X locks to commit.
Exam notes (the dense version)

Lock modes: shared (S) for reads, exclusive (X) for writes; S–S is compatible, everything else conflicts. 2PL: a growing phase (only locks) then a shrinking phase (only unlocks). 2PL ensures conflict serializability (in order of lock points) but allows deadlock and cascading aborts. Strict 2PL keeps X locks until commit (strict schedules); rigorous 2PL keeps all locks until commit. Deadlock = a cycle in the wait-for graph.

Previous year questions: Transactions & Concurrency Control (15)

PYQs are grouped by topic, so this is the full set for Transactions & Concurrency Control; try the ones that match this subtopic. Open all 15 on the topic page.