chapter 12 transactions 12.1 introduction 12.2 transactions 12.3nested transactions 12.4 locks
TRANSCRIPT
Chapter 12 Transactions
12.1 Introduction
12.2 Transactions
12.3Nested Transactions
12.4 Locks
Introduction
• Transaction– A sequence of server operations that is
guaranteed by the server to be• Atomic in the presence of multiple client and server
crashes.
• Nested transaction– Structured from sets of other transactions– Allow additional concurrency
Introduction
• Goal of transaction– To ensure all of objects managed by a server
remain in consistent state when • accessed by multiple transactions• in the presence of server crashes
• Server guarantee– Entire transaction is carried out and results
permanently recorded– If crash completely erased
Introduction
• Transactions deal with – Crash failures of processes and omission
failures of communications
• Do not deal with– Arbitrary behavior
Simple Synchronization (without Transactions)
• Synchronizing client operations without recourse to transactions– Atomic Operations– Synchronization of server operations (to
enhance client cooperation)
Atomic Transactions
• Operations that are free from interference from concurrent operations being performed in other threads– Using synchronized methods in Java– Use of any available mutual exclusion
mechanism (mutex)
Synchronization of server operations
• Prevent threads interfering with one another– Some clients using operations to update the
server’s objects while other clients use operations to access them (producer consumer model)
• Java wait and notify used within synchronized methods (allows threads to communicate)
Failure model for transactions
• Lampson’s Fault model– Writes to permanent storage may fail– Servers may crash– There may be arbitrary delay before a message
arrives
Figure 12.1
deposit(amount)deposit amount in the account
withdraw(amount)withdraw amount from the account
getBalance() -> amountreturn the balance of the account
setBalance(amount)set the balance of the account to amount
Operations of the Branch interface
Operations of the Account interface
create(name) -> accountcreate a new account with a given name
lookUp(name) -> account return a reference to the account with the given name
branchTotal() -> amountreturn the total of all the balances at the branch
Atomicity
Stateful servers have two requirements
1.Accesses from different clients shouldn't interfere with each other
2.Clients should get fast access to the server
We define atomicity as
All or Nothing • A client's operation on a server's resource should
complete successfully, and the results hold thereafter (even if server crash), or it should fail and the resource should show no effect of the failed operation
Isolation • Each operation should proceed without interference
from other clients' operations - intermediate effects should not be visible.
All or nothing
• Failure atomicity- effects are atomic even when the server crashes
• Durability-after a transaction has completed successfully all its effects are saved in permanent storage.
Example of Atomicity
Mutual Exclusion • For a multi-threaded server, if two or more threads
attempt to modify the same piece of data, then the updates should have mutual exclusion around the updates to provide isolation, using semaphores or monitors
Synchronization • In situations such as Producer Consumer, need to allow
one operation to finish so second operation can use results, needing isolation.
ACIDAtomicity
• Either all or none of the Transaction's operations are performed. If a transaction is interrupted by failure, then partial changes are undone
Consistency • System moves from one self-consistent state to another
Isolation • An incomplete transaction never reveals partial state or changes
before committing
Durability • After committing, the system never loses the results of the
transaction, independent of any subsequent failure
Figure 12.2 A clients banking transactions
Transaction T:a.withdraw(100);b.deposit(100);c.withdraw(200);b.deposit(200);
Transactions
• Transactions are technique for grouping operations on data so that either all complete or none complete
openTransaction() -> trans;starts a new transaction and delivers a unique TID trans. This identifier will be used in the other operations in the transaction.
closeTransaction(trans) -> (commit, abort);ends a transaction: a commit return value indicates that the transaction has committed; an abort return value indicates that it has aborted.
abortTransaction(trans);aborts the transaction.
Coordinator Interface
Transaction life history
Successful Aborted by client Aborted by server
openTransaction openTransaction openTransactionoperation operation operation operation operation operation
server abortstransaction
operation operation operation ERRORreported to client
closeTransaction abortTransaction
Transaction T :
balance = b.getBalance();b.setBalance(balance*1.1);a.withdraw(balance/10)
Transaction U:
balance = b.getBalance();b.setBalance(balance*1.1);c.withdraw(balance/10)
balance = b.getBalance(); $200
balance = b.getBalance(); $200
b.setBalance(balance*1.1); $220
b.setBalance(balance*1.1); $220
a.withdraw(balance/10) $80
c.withdraw(balance/10) $280
The Lost Update Problem
Transaction V:
a.withdraw(100)b.deposit(100)
Transaction W:
aBranch.branchTotal()
a.withdraw(100); $100
total = a.getBalance() $100
total = total+b.getBalance() $300
total = total+c.getBalance()
b.deposit(100) $300
The Inconsistent retrievals problem
Serial Equivalence
• Two transactions are serial if all the operations in one transaction precede the operations in the other.
• Two operations are in conflict if: – At least one is a write – They both act on the same data – They are issued by different transactions
Operations of differenttransactions
Conflict Reason
read read No Because the effect of a pair of read operationsdoes not depend on the order in which they areexecuted
read write Yes Because the effect of a read and a write operationdepends on the order of their execution
write write Yes Because the effect of a pair of write operationsdepends on the order of their execution
Read and Write operation conflict rules
Serial Equivalence cont.
• Definition: Two schedules are computationally equivalent if:
• The same operations are involved (possibly reordered)
• For every pair of operations in conflict, the same operation appears first in each schedule
• So, a schedule is serialisable if the schedule is computationally equivalent to a serial schedule.
Transaction T:
balance = b.getBalance()b.setBalance(balance*1.1)a.withdraw(balance/10)
Transaction U:
balance = b.getBalance()b.setBalance(balance*1.1)c.withdraw(balance/10)
balance = b.getBalance() $200
b.setBalance(balance*1.1) $220balance = b.getBalance() $220
b.setBalance(balance*1.1) $242
a.withdraw(balance/10) $80 c.withdraw(balance/10) $278
A serially equivalent interleaving of T and U
Transaction T: Transaction U:
x = read(i)
write(i, 10)y = read(j)
write(j, 30)
write(j, 20)z = read (i)
A non-serially equivalent interleaving of T and U
Serial equivalent objects require one of the following two conditions:
• T accesses i before U and T accesses j before U
• U accesses i before T and U accesses j before T
Transaction T:
a.getBalance()a.setBalance(balance + 10)
Transaction U:
a.getBalance()a.setBalance(balance + 20)
balance = a.getBalance() $100
a.setBalance(balance + 10) $110
balance = a.getBalance() $110
a.setBalance(balance + 20) $130
commit transaction
abort transaction
A dirty read when transaction T aborts
Transaction T:
a.setBalance(105)
Transaction U:
a.setBalance(110)
$100
a.setBalance(105) $105
a.setBalance(110) $110
Overwriting uncommitted values: Premature Writes
More on Recoverability from aborts
• Strict execution of transactions– Transaction delay both their read and write
operations to avoid dirty reads and premature writes
– Enforces isolation
• Tentative versions
– Each transaction is provided with its own private set of tentative versions of an object that it has altered
– All updated operations of a transaction store Values in the transactions own private set.
– Access operations in a transaction take values from the transaction’s own private set if possible or failing that from the objects
– The tentative versions are transferred to the objects only when a transaction commits
– This is performed in a single step during which other transactions are excluded from access to the objects being altered
– When the object aborts the tentative versions are deleted.
Tentative version
Exercise 12.3
• Give serially equivalent interleavings of T and U in Exercise 12.2 with the following properties: (1) that is strict; (2) that is not strict but could not produce cascading aborts; (3) that could produce cascading aborts.
1. Strict
Tx:=read(j)y:=read(i)
write(j,44)write(i,33)Commit
U
x:=read(k)
write(i,55)y:=read(j)write(k,66)
2. No cascading aborts
Tx:=read(j)y:=read(i)
write(j,44)write(i,33) Commit
U
x:=read(k)
write(i,55)
y:=read(j)write(k,66)
3. Cascading aborts
Tx:=read(j)
y:=read(i)
write(j,44)write(i,33)
U
x:=read(k)write(i,55)
y:=read(j)write(k,66)Commit
Nested Transactions
• Transactions may themselves be composed of multiple transactions
• For example: Transfer is a composition of withdraw and deposit transactions, which are themselves composed of read and write transactions
• Benefits: – Nested transactions can run concurrently with other
transactions at same level in hierarchy – If lower levels abort, may not need to abort whole
transaction. Can instead use other means of recovery.
T : top-level transactionT1 = openSubTransaction T2 = openSubTransaction
openSubTransaction openSubTransactionopenSubTransaction
openSubTransaction
T1 : T2 :
T11 : T12 :
T211 :
T21 :
prov.commit
prov. commit
abort
prov. commitprov. commit
prov. commit
commit
Nested Transactions
Rules for commitment of nested transactions
• A transaction may commit or abort only after its child transactions have completed
• When a subtransaction completes, it makes an independent decision either to commit or to abort. An abort is final
• When a parent aborts, all of its subtransactions are aborted. • When a subtransaction aborts the parent can decide whether
or not to abort. • If the top-level transaction commits then all of the
subtransactions that have provisionally committed can also commit, provided none of their ancestors have aborted.
Transaction T: balance = b.getBalance()b.setBalance(bal*1.1)a.withdraw(bal/10)
Transaction U:
balance = b.getBalance()b.setBalance(bal*1.1)c.withdraw(bal/10)
Operations Locks Operations Locks
openTransactionbal = b.getBalance() lock B
b.setBalance(bal*1.1) openTransaction
a.withdraw(bal/10) lock A bal = b.getBalance() waits for T’slock on B
closeTransaction unlock A, B lock B
b.setBalance(bal*1.1)
c.withdraw(bal/10) lock C
closeTransaction unlock B, C
Transactions T and U with exclusive locks
For one object Lock requested read write
Lock already set none OK OK
read OK wait
write wait wait
Figure 12-15: Lock Compatibility
1. When an operation accesses an object within a transaction:(a) If the object is not already locked, it is locked and the operation
proceeds.(b) If the object has a conflicting lock set by another transaction, the
transaction must wait until it is unlocked.(c) If the object has a non-conflicting lock set by another transaction, the
lock is shared and the operation proceeds.(d) If the object has already been locked in the same transaction, the lock
will be promoted if necessary and the operation proceeds. (Where promotion is prevented by a conflicting lock, rule (b) is used.)
2. When a transaction is committed or aborted, the server unlocks all objects it locked for the transaction.
Figure 12-16:Use of Locks in strict two-phase locking
public class Lock {private Object object; // the object being protected by the lockprivate Vector holders; // the TIDs of current holdersprivate LockType lockType; // the current type public synchronized void acquire(TransID trans, LockType aLockType ){
while(/*another transaction holds the lock in conflicing mode*/) {try {
wait();}catch ( InterruptedException e){/*...*/ }
} if(holders.isEmpty()) { // no TIDs hold lock holders.addElement(trans);
lockType = aLockType; } else if(/*another transaction holds the lock, share it*/ ) ){ if(/* this transaction not a holder*/) holders.addElement(trans);
} else if (/* this transaction is a holder but needs a more exclusive lock*/) lockType.promote(); }
}
Figure 12.17 Lock Class
public synchronized void release(TransID trans ){holders.removeElement(trans); // remove this holder// set locktype to nonenotifyAll();
}}
Figure 12.17 Lock Class Cont.
public class LockManager { private Hashtable theLocks;
public void setLock(Object object, TransID trans, LockType lockType){ Lock foundLock; synchronized(this){
// find the lock associated with object // if there isn’t one, create it and add to the hashtable } foundLock.acquire(trans, lockType); }
// synchronize this one because we want to remove all entries public synchronized void unLock(TransID trans) { Enumeration e = theLocks.elements(); while(e.hasMoreElements()){ Lock aLock = (Lock)(e.nextElement()); if(/* trans is a holder of this lock*/ ) aLock.release(trans); } }}
Figure 12.17 LockManager Class
Transaction T Transaction U
Operations Locks Operations Locks
a.deposit(100); write lock A
b.deposit(200) write lock B
b.withdraw(100)waits for U’s a.withdraw(200); waits for T’s
lock on B lock on A
Figure 12.19: Deadlock with write locks
B
A
Waits for
Held by
Held by
T UU T
Waits for
Figure 12.20The wait-for graph for Figure
12.19
U
V
T
Figure 12.21A cycle in a wait-for graph
C
T
UV
Held by
Held by
Held by
T
U
V
W
W
B
Held by
Waits for
Figure 12.22Another wait-for graph
Conditions for Deadlock
1. Limited access (eg mutex or finite buffer)
2. No preemption (if someone has resource can't take it away)
3. Hold and wait. Independent threads must possess some of its needed resources and waiting for the remainder to become free.
4. Circular chain of requests and ownership.
Deadlock prevention
• Lock all of the objects used by a transactions when it starts– Problems: sometimes impossible to predict
objects that will be used, unnecessarily restricts access to shared resources
• Requesting locks on objects in a predefined order– May result in premature locking and reduction
in concurrency
Deadlock Detection
• Finding cycles in the wait-for-graph
• Having detected a deadlock a transaction must be selected for abortion to break the cycle
Transaction T Transaction U
Operations Locks Operations Locks
a.deposit(100); write lock A
b.deposit(200) write lock B
b.withdraw(100)
waits for U’s a.withdraw(200); waits for T’s
lock on B lock on A (timeout elapses) T’s lock on A becomes vulnerable,
unlock A, abort Ta.withdraw(200); write locks A
unlock A, B
Figure 12.23Resolution of the deadlock in Figure 15.19
For one object Lock to be set
read write commit Lock already set none OK OK OK
read OK OK wait
write OK wait
commit wait wait
Lock compatibility (read, write and commit locks)
Exercise 12.10
• Consider a relaxation of two-phase locks in which read only transactions can release read locks early.– Would a read only transaction have consistent
retrievals?– Would the objects become inconsistent?
Answers to 12.10
• There is no guarantee of consistent retrievals because overlapping transactions can alter the objects after they are unlocked.
• No the database would not become inconsistent.