Sub topic 9
Shared and exclusive locks and the compatibility matrix
This chapter assumes you can build a precedence graph and test conflict serializability, and that you know what recoverable and cascadeless schedules are. It also assumes you know the read-write, write-read and write-write conflicts. Here we add the first tool a database uses to enforce those rules: locks with two modes, shared and exclusive. The next chapter combines them into two-phase locking.
Why locks exist
A scheduler could check each finished schedule for serializability, but a database cannot run first and check afterwards. It must stop bad interleavings while they happen. A lock is a flag on a data item that a transaction must hold before it touches the item. The lock manager decides whether to grant each request. A transaction that is refused waits until the conflicting lock is released.
A single kind of lock would work, but it would be too strict. Two transactions that only read the same item do not conflict, so they should not block each other. Two lock modes capture this.
The two lock modes
- Shared lock, S. Taken with
lock-S(Q). The holder may read Q but not write it. Many transactions can hold S on the same item at once. - Exclusive lock, X. Taken with
lock-X(Q). The holder may read and write Q. No other transaction can hold any lock on Q while X is held.
A transaction releases a lock with unlock(Q). Before every read(Q) the transaction must hold at least S on Q. Before every write(Q) it must hold X on Q. A request that breaks these rules is a protocol error, not a wait.
The modes mirror the conflict definition. Two operations conflict when they touch the same item, come from different transactions, and at least one is a write. S represents reads, which never conflict with each other. X represents writes, which conflict with everything.
The compatibility matrix
Two lock modes are compatible if two different transactions can hold them on the same item at the same time. The lock manager consults this matrix on every request.
| Held by another transaction ↓ / Requested → | S | X |
|---|---|---|
| S | Yes | No |
| X | No | No |
Only one of the four cells allows a grant: S requested while others hold S. In GATE questions the matrix is usually implied rather than shown, so memorize it as a rule: S is compatible only with S.
The matrix looks only at locks held by other transactions. A transaction never conflicts with itself. If T1 holds S on A and asks for X on A, the only question is whether any other transaction holds a lock on A.
How the lock manager decides
Real lock managers keep a lock table. Each item has a list of granted locks and a queue of waiting requests. When a lock is released, the manager looks at the queue and grants what is now compatible.
A runnable model
The following program implements the matrix rule for granting. It does not keep a waiting queue. A refused request just returns False.
class LockManager:
def __init__(self):
self.held = {} # item -> {txn: 'S' or 'X'}
def request(self, txn, item, mode):
holders = self.held.setdefault(item, {})
others = [m for t, m in holders.items() if t != txn]
if mode == 'S':
ok = all(m == 'S' for m in others)
else:
ok = not others
if ok:
if holders.get(txn) != 'X': # never downgrade by asking for S
holders[txn] = mode
return True
return False
def release(self, txn, item):
self.held.get(item, {}).pop(txn, None)
lm = LockManager()
print(lm.request('T1', 'A', 'S')) # True: nobody else holds A
print(lm.request('T2', 'A', 'S')) # True: S is compatible with S
print(lm.request('T3', 'A', 'X')) # False: T1 and T2 hold S
lm.release('T2', 'A')
print(lm.request('T1', 'A', 'X')) # True: upgrade, no other holder remains
print(lm.request('T3', 'A', 'S')) # False: T1 now holds XThe fourth request is a lock upgrade, discussed next.
Lock conversion
A transaction often starts by reading an item and later decides to write it. Instead of releasing S and asking for X, it can convert the lock.
| Conversion | Name | When it succeeds |
|---|---|---|
| S → X | Upgrade | Only when no other transaction holds S on the item |
| X → S | Downgrade | Always allowed, and it may let waiting readers proceed |
Upgrades are a common source of deadlock. Suppose T1 and T2 both hold S on A and both request an upgrade to X. Each waits for the other to release S, so neither can proceed. Deadlock handling is a later chapter.
The SQL pattern SELECT ... FOR UPDATE avoids this by asking for X at the first read. The second session then waits at the SELECT, not at the UPDATE, so the two sessions never hold S at the same time.
-- Session 1 -- Session 2
BEGIN; BEGIN;
SELECT balance FROM account SELECT balance FROM account
WHERE id = 1 FOR UPDATE; WHERE id = 1 FOR UPDATE; -- blocks here
UPDATE account SET balance = balance - 100
WHERE id = 1;
COMMIT; -- now proceeds and reads the committed balance
UPDATE account SET balance = balance - 50
WHERE id = 1;
COMMIT;Without FOR UPDATE, both sessions could read the same balance and one update would overwrite the other. This is the lost update anomaly from earlier in the tutorial.
Locks alone do not guarantee serializability
Obeying the compatibility matrix prevents two transactions from touching an item in incompatible ways at the same instant. It does not control when a transaction releases its locks. Consider T1, which moves 50 from A to B, and T2, which reads A and B to compute a total.
| Step | T1 | T2 |
|---|---|---|
| 1 | lock-X(A) | |
| 2 | read(A), write(A) | |
| 3 | unlock(A) | |
| 4 | lock-S(A), read(A), unlock(A) | |
| 5 | lock-S(B), read(B), unlock(B) | |
| 6 | lock-X(B) | |
| 7 | read(B), write(B), unlock(B) |
Every request is compatible with the locks held at that moment. Yet T2 sees A after T1's update and B before it, so its total is wrong by 50. The precedence graph explains why. T1 writes A before T2 reads it, which gives the edge T1 → T2. T2 reads B before T1 writes it, which gives T2 → T1. The graph has a cycle, so the schedule is not conflict serializable.
The cause is that T1 released A and then locked B afterward. Locking gives mutual exclusion on one item. Serializability across items needs a rule about the order of lock and unlock operations. That rule is two-phase locking.
Locking and recoverability
Locks also affect recoverability, depending on when X locks are released. If T1 releases its X lock on A before it commits, T2 can read the uncommitted value of A. That is a dirty read, and if T1 aborts, T2 must abort too (a cascading rollback). Holding every X lock until commit prevents this, which is the idea behind strict locking in the next chapter.
Starvation
A request is refused when it conflicts with a granted lock. Suppose T3 waits for X on A while a stream of transactions keep acquiring S on A. Each new S request is compatible with the current S holders, so a naive manager grants it. T3 may wait forever. This is starvation.
The usual fix is a fair queueing rule. A new request is granted only if it is compatible with all granted locks and no earlier request is still waiting. Under that rule, new readers queue behind T3.
Common errors in GATE questions
- Treating X as compatible with S. It is not. Any pair that includes an X is incompatible.
- Checking the matrix against your own locks. A transaction's own locks never block it.
- Assuming locking implies serializability. The example above follows every compatibility rule and still produces a cycle.
- Forgetting that a read needs a lock too. A transaction that reads without lock-S is breaking the protocol.
- Ignoring waits when listing a schedule. If a request is refused, the transaction's later operations cannot appear until the lock is granted.
Summary
- S locks allow reading and X locks allow reading and writing.
- S is compatible only with S. Every other pair of modes conflicts.
- Upgrades succeed only when the requester is the sole holder. Downgrades always succeed.
- Compatible grants alone do not give serializability. The order of lock and unlock steps matters, and the next chapter covers it.
Exercise
T1 holds S on item P. T2 holds S on item P. T3 holds S on item Q. For each of the following new requests, say whether it is granted: (a) T4 requests X on P. (b) T4 requests S on P. (c) T3 requests X on Q. (d) T1 requests X on P.
Show answer
(a) Refused. X conflicts with the S locks held by T1 and T2. (b) Granted. S is compatible with S. (c) Granted. T3 is the only holder of a lock on Q, and a transaction does not conflict with itself, so this is an upgrade. (d) Refused. This is an upgrade, but T2 still holds S on P, so T1 must wait until T2 releases it.
Exercise
T1 and T2 both hold S on A. Each then requests an upgrade to X on A. What happens, and how does SELECT ... FOR UPDATE avoid it?
Show answer
Each upgrade is refused because the other transaction still holds S, and neither releases it while waiting. The two transactions are deadlocked. With SELECT ... FOR UPDATE, the first reader takes X immediately. The second session blocks at its first read, so the two never hold S together and no upgrade conflict can arise.
Exercise
In the T1/T2 table above, state the two precedence edges and explain why the schedule is not conflict serializable even though every lock request obeyed the compatibility matrix.
Show answer
T1 writes A before T2 reads A, giving T1 → T2. T2 reads B before T1 writes B, giving T2 → T1. These edges form a cycle, so no equivalent serial order exists. The matrix only prevents incompatible locks from being held at the same time. It says nothing about T1 unlocking A before it has locked B, which is what lets T2 slip between T1's two updates.