Locks
Locks
Locks
Transaction T: Transaction U:
balance = b.getBalance() balance = b.getBalance()
b.setBalance(bal*1.1) b.setBalance(bal*1.1)
a.withdraw(bal/10) c.withdraw(bal/10)
Operations Locks Operations Locks
openTransaction
bal = b.getBalance() lock B
b.setBalance(bal*1.1) openTransaction
a.withdraw(bal/10) Lock A bal = b.getBalance() waits for T’s
lock on B
closeTransaction unlock A, B
lock B
b.setBalance(bal*1.1)
c.withdraw(bal/10) lock C
closeTransaction unlock B, C
Figure:
Lock compatibility
T1 (Transfer) T2 (Dividend)
Two phase locking – definition
Transaction T Transaction U
Waits for B
Held by
Figure:
A cycle in a wait-for graph
V
How to avoid deadlocks?
1. Deadlock Prevention
2. Deadlocks detection
Deadlock Prevention
Deadlock prevention:
Simple way is to lock all of the objects used by a
transaction when it starts. It should be done as an atomic
action to prevent deadlock. a. inefficient, say lock an
object you only need for short period of time. b. Hard to
predict what objects a transaction will require.
Judge if system can remain in a Safe state by satisfying a
certain resource request. Banker’s algorithm.
Order the objects in certain order. Acquiring the locks
need to follow this certain order.
Deadlock Detection
Transaction T Transaction U
Operations Locks Operations Locks
Transaction T Transaction U
Operations Locks Operations Locks
Tv Ti Rule
write read 1. Ti must not read objects written by Tv
read write 2. Tv must not read objects written by Ti
write write 3. Ti must not write objects written by Tv and
Tv must not write objects written by Ti
T1
Earlier committed
transactions
T2
T3
Transaction
being validated Tv
active
1
Later active
active
transactions 2
Validation
Rule Tc Ti
1. write read Tc must not write an object that has been read by any Ti where Ti >Tc
this requires that Tc ≥ the maximum read timestamp of the object.
2. write write Tc must not write an object that has been written by any Ti where Ti >Tc
this requires that Tc > write timestamp of the committed object.
3. read write Tc must not read an object that has been written by any Ti whereTi >Tc
this requires that Tc > write timestamp of the committed object.
Figure:
Write operations and timestamps
T2 T1 T2 Key:
Before Before Ti
Committed
After T2 T3 After T1 T2 T3
Ti
Time Time
Tentative
object produced
(c) T3 write (d) T3 write by transaction Ti
Transaction (with write timestamp Ti)
T1 T4 T4 aborts T1<T2<T3<T4
Before Before
After T1 T3 T4 After T4
Time Time
Timestamp ordering write rule
(b) T3 read
(a) T3 read
Key:
read read
T2 T2 T4 proceeds
proceeds Ti
Selected Committed
Selected Time
Time
Ti
(c) T3 read (d) T3 read
Tentative