Two-phase locking (2PL) in DBMS Theory - Time & Space Complexity
When using two-phase locking (2PL) in databases, we want to understand how the locking process affects the time it takes to complete transactions.
We ask: How does the number of locks and their management grow as more data is accessed?
Analyze the time complexity of the following simplified 2PL locking steps.
BEGIN TRANSACTION;
-- Growing phase: acquire locks on n data items
FOR EACH data_item IN transaction_items LOOP
LOCK(data_item);
END LOOP;
-- Shrinking phase: release locks after operations
FOR EACH data_item IN transaction_items LOOP
UNLOCK(data_item);
END LOOP;
COMMIT;
This code shows a transaction acquiring locks on all its data items before releasing any, following the two-phase locking protocol.
Look at the loops that repeat actions:
- Primary operation: Locking each data item in the growing phase.
- How many times: Once for each data item accessed, so n times.
As the number of data items (n) increases, the number of lock and unlock operations grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (10 locks + 10 unlocks) |
| 100 | About 200 (100 locks + 100 unlocks) |
| 1000 | About 2000 (1000 locks + 1000 unlocks) |
Pattern observation: The total locking work grows directly with the number of data items accessed.
Time Complexity: O(n)
This means the time to manage locks grows in a straight line as you access more data items.
[X] Wrong: "Locking all data items at once takes constant time regardless of how many items there are."
[OK] Correct: Each data item needs its own lock operation, so the total time grows with the number of items, not stays the same.
Understanding how locking scales helps you explain database behavior clearly and shows you grasp how transactions manage data safely and efficiently.
"What if the transaction acquires locks only when needed instead of all at once? How would the time complexity change?"