Вы находитесь на странице: 1из 64

Transaction Management

Concurrrency Control

Connolly & Begg.


Pearson Education 2009

Transaction Support

Transaction: Action, or series of actions, carried out by user or application, which reads or updates contents of database.

Logical unit of work on the database.


Application program is series of transactions with nondatabase processing in between.

Transforms database from one consistent state to another, although consistency may be violated during transaction.

Example Transaction

Transaction Support
Can

have one of two outcomes:

Success - transaction commits and database reaches a new consistent state. Failure - transaction aborts, and database must be restored to consistent state before it started. Such a transaction is rolled back or undone.
Committed

transaction cannot be aborted. Aborted transaction that is rolled back can be restarted later.
4

Properties of Transactions
Four

basic (ACID) properties of a transaction are:

Atomicity All or nothing property. Consistency Must transform database from one consistent state to another. Isolation Partial effects of incomplete transactions should not be visible to other transactions. Durability Effects of a committed transaction are permanent and must not be lost because of later failure.

DBMS Transaction Subsystem

Concurrency Control
Process of managing simultaneous operations on the database without having them interfere with one another.

Prevents interference when two or more users are accessing database simultaneously and at least one is updating data. Although two transactions may be correct in themselves, interleaving of operations may produce an incorrect result.

Need for Concurrency Control


Three

examples of potential problems caused by concurrency: Lost update problem. Uncommitted dependency problem. Inconsistent analysis problem.

Lost Update Problem


Successfully completed update is overridden by another user.

Example: T1 withdrawing 10 from an account with balx, initially 100. T2 depositing 100 into same account. Serially, final balance would be 190.

Lost Update Problem

T2s

update is lost ! This can be avoided by preventing T1 from reading balx until after update.
10

Uncommitted Dependency Problem


Occurs when one transaction can see intermediate results of another transaction before it has committed.

Example: T4 updates balx to 200 but it aborts, so balx should be back at original value of 100. T3 has read new value of balx (200) and uses value as basis of 10 reduction, giving a new balance of 190, instead of 90.
11

Uncommitted Dependency Problem

Problem

avoided by preventing T3 from reading balx until after T4 commits or aborts.


12

Inconsistent Analysis Problem


Occurs when transaction reads several values but second transaction updates some of them during execution of first. Sometimes referred to as dirty read or unrepeatable read. Example: T6 is totaling balances of account x (100), account y (50), and account z (25). Meantime, T5 has transferred 10 from balx to balz, so T6 now has wrong result (10 too high).
13

Inconsistent Analysis Problem

Problem avoided by preventing T6 from reading balx and balz until after T5 completed updates.
14

Serializability some definitions


Schedule: time ordered sequence of reads/writes by set of concurrent transactions. Serial Schedule: Schedule where operations of each transaction are executed consecutively without any interleaved operations from other transactions. Nonserial schedule: Schedule where operations from set of concurrent transactions are interleaved. We want to find nonserial schedules that are equivalent to some serial schedule. Such a schedule is called serializable.

15

Serializability

In serializability, ordering of read/writes is important: (a) If two transactions only read a data item, they do not
conflict and order is not important. (b) If two transactions either read or write completely separate data items, they do not conflict and order is not important. (c) If one transaction writes a data item and another reads or writes same data item, order of execution is important.

16

Example of Conflict Serializability

17

Serializability
Conflict

serializable schedule orders any conflicting operations in same way as some serial execution. Constrained write rule: transaction updates data item based on its old value, which is first read. Under the constrained write rule we can use precedence graph to test for serializability

18

Precedence Graph
Create:

node for each transaction; a directed edge Ti Tj, if Tj reads the value of an item written by TI; a directed edge Ti Tj, if Tj writes a value into an item after it has been read by Ti. If precedence graph contains cycle schedule is not conflict serializable.

19

Example - Non-conflict serializable schedule

20

View Serializability
Offers less stringent definition of schedule equivalence than conflict serializability. Two schedules S1 and S2 are view equivalent if:

For each data item x, if Ti reads initial value of x in S1, Ti must also read initial value of x in S2. For each read on x by Ti in S1, if value read by x is written by Tj, Ti must also read value of x produced by Tj in S2. For each data item x, if last write on x performed by Ti in S1, same transaction must perform final write on x in S2.
21

View Serializability
Schedule

is view serializable if it is view equivalent to a serial schedule. Every conflict serializable schedule is view serializable, although converse is not true.

22

Example - View Serializable schedule

23

Exercise
Consider the following schedule

Determine whether the schedule is conflict serialisable and/or view serialisable.


24

Recoverability
Serializability

identifies schedules that maintain database consistency, assuming no transaction fails. Recoverable Schedule: A schedule where, for each pair of transactions Ti and Tj, if Tj reads a data item previously written by Ti, then the commit operation of Ti precedes the commit operation of Tj.

25

Exercise 2
Consider the following schedule

Determine if the schedule is: conflict serialisable view serialisable recoverable


26

How can the DBMS ensure serializability?

27

Locking
Most widely used approach to ensure serializability. Transaction uses locks to deny access to other transactions and so prevent incorrect updates. Generally, a transaction must claim a shared (read), or exclusive (write) lock on a data item before read or write.

28

Locking - Basic Rules


If transaction has shared lock on item, can read but not update item. If transaction has exclusive lock on item, can both read and update item. Reads cannot conflict, so more than one transaction can hold shared locks simultaneously on same item. Exclusive lock gives transaction exclusive access to that item. Some systems allow transaction to upgrade read lock to an exclusive lock, or downgrade exclusive lock to a shared lock.

29

Two-Phase Locking (2PL)


Transaction follows 2PL protocol if all locking operations precede first unlock operation in the transaction.

Two phases for transaction: Growing phase - acquires all locks but cannot release any locks. Shrinking phase - releases locks but cannot acquire any new locks.
30

Preventing Lost Update Problem using 2PL

31

Preventing Uncommitted Dependency Problem using 2PL

32

Preventing Inconsistent Analysis Problem using 2PL

33

2PL doesnt solve every potential problem. T1


W(B)
R(A) W(A) R(A) R(B) W(B)

T2

We should never have let T1 commit.

T1 commits

Cascading rollback
34

Now T2 aborts!

How do we deal with this?


Commit trans T only after all transactions that wrote data that T read have committed Or only let a transaction read an item after the transaction that last wrote this item has committed Strict 2PL: 2PL + a transaction releases its locks only after it has committed. How does Strict 2PL prevent cascading rollback?

35

Summary
Concurrency

control is a scheduling problem of actions of different tranactions

Serial Schedules
Conflict-serializable Schedules Serializable Schedules

Two-Phase Locking

36

Deadlock
An impasse that may result when two (or more) transactions are each waiting for locks held by the other to be released.

37

Deadlock possible solutions?


Only one way to break deadlock: abort one or more of the transactions. Deadlock should be transparent to user, so DBMS should restart transaction(s). Three general techniques for handling deadlock: Timeouts. Deadlock prevention. Deadlock detection and recovery.

38

Timeouts
Transaction

that requests lock will only wait for a system-defined period of time. If lock has not been granted within this period, lock request times out. In this case, DBMS assumes transaction may be deadlocked, even though it may not be, and it aborts and automatically restarts the transaction.

39

Deadlock Prevention
DBMS

looks ahead to see if transaction would cause deadlock and never allows deadlock to occur. Could order transactions using transaction timestamps: Wait-Die - only an older transaction can wait for younger
one, otherwise transaction is aborted (dies) and restarted with same timestamp. Wound-Wait - only a younger transaction can wait for an older one. If older transaction requests lock held by younger one, younger one is aborted (wounded).

40

Deadlock Detection and Recovery


DBMS allows deadlock to occur but recognizes it and breaks it. Usually handled by construction of wait-for graph (WFG) showing transaction dependencies:

Create a node for each transaction. Create edge Ti -> Tj, if Ti waiting to lock item locked by Tj.

Deadlock exists if and only if WFG contains cycle. WFG is created at regular intervals.

41

Example - Wait-For-Graph (WFG)

42

Recovery from Deadlock Detection

Several issues: choice of deadlock victim; how far to roll a transaction back; avoiding starvation.

43

Exercise
Consider the following schedule involving three transactions T1, T2 and T3:
Time 1 2 3 4 5 6 7 8 9 10 11 12 T1 T2 W(A) R(B) R(C) W(C)
W(C) Commit W(B) W(C)

T3

W(B)

R(A)
Commit Commit

Describe how the strict two-phase locking protocol with headlock detection would handle the schedule. 44

Exercise
Consider the same schedule involving three transactions T1, T2 and T3:
Time 1 2 3 4 5 6 7 8 9 10 11 12 T1 T2 W(A) R(B) R(C) W(C)
W(C) Commit W(B) W(C)

T3

W(B)

R(A)
Commit Commit

Describe how the strict two-phase locking with wound-wait deadlock prevention would handle the schedule.

45

Other Approaches for Concurrency Control


When something goes wrong, abort and restart a transaction that tries to engage in unserializable behavior Timestamping
Assign a timestamp to each transaction Record the timestamps of transactions that last read and write each database element

Validation
Maintain a record of what active transactions are doing
46

Timestamping
Transactions ordered globally so that older transactions, transactions with smaller timestamps, get priority in the event of conflict. Conflict is resolved by rolling back and restarting transaction. No locks so no deadlock. Timestamp: A unique identifier created by DBMS that indicates relative starting time of a transaction.

47

Timestamping - definition
Timestamping: a concurrency control protocol that orders transactions in such a way that older transactions get priority in the event of a conflict. Read/write proceeds only if last update on that data item was carried out by an older transaction. Otherwise, transaction requesting read/write is restarted and given a new timestamp. Also timestamps for data items:

read-timestamp - timestamp of last transaction to read item; write-timestamp - timestamp of last transaction to write item. 48

Assumed Serial Schedule

Conflict serializable schedule that is equivalent to a serial schedule in which the timestamp order of transactions is the order to execute them

Actual schedule T starts U starts V starts

Serial schedule
T starts U starts V starts

Timestamping: how does the protocol work?


A transaction T with timestamp ts(T) wants to read(x): ts(T) < write_timestamp(x) x already updated by younger (later) transaction. Transaction T must be aborted and restarted with a new timestamp. ts(T) write_timestamp(x) transaction can proceed read_timestamp = max(ts(T), read_timestamp(x))
50

Timestamping: how does the protocol work?


A transaction T with timestamp ts(T) wants to write(x): ts(T) < read_timestamp (x)
younger transaction has read the value x rollback transaction T and restart using a later timestamp

ts(T) < write_timestamp(x)


x already written by younger transaction. Write can safely be ignored - ignore obsolete write rule.

all other cases: operation accepted and executed.


51

Example
T1 200 r1(B) Transactions T2 T3 150 175 Database elements A B C RT=0 RT=0 RT=0 WT=0 WT=0 WT=0 RT=200

RT=150 r2(A) RT=175 rtoo 3(c) Writing w1(B) WT=200 late! WT=200 w1(A) w2(C) Abort; w3(A) WT=175 52

Timestamps vs. Locks


Time stamps
Superior if
most transactions are read-only rare that concurrent transactions will read or write the same element

Locks
Superior in high-conflict situations Frequently delay transactions as they wait for locks

In high-conflict situations, rollback will be frequent, introducing more delays than a locking system

53

Comparison of Methods

54

Concurrency Control by Validation


Another

optimistic concurrency control Maintains a record of what active transactions are doing Just before a transaction starts to write, it goes through a validation phase If a there is a risk of physically unrealizable behavior, the transaction is rolled back Potentially allows greater concurrency than traditional protocols.

55

Validation-based Scheduler

Keep track of each transaction Ts Read set RS(T): the set of elements T read Write set WS(T): the set of elements T write Execute transactions in three phases: 1. Read. T reads all the elements in RS(T) 2. Validate. Validate T by comparing its RS(T) and WS(T) with those in other transactions. If the validation fails, T is rolled back 3. Write. T writes its values for the elements in WS(T)
56

Scheduler Maintains Information Sets


START:

the set of transactions that have started, but not yet completed validation. For each T, maintain (T, START(T)) VAL: the set of transactions that have been validated, but not yet finished. For each T, maintain (T, START(T), VAL(T)) FIN: the set of transaction that have completed. For each T, maintain (T, START(T), VAL(T), FIN(T))

57

Assumed Serial Schedule for Validation


We

may think of each transaction that successfully validates as executing at the moment that it validates

Actual schedule T validates Serial schedule T validates U validates V validates


58

U validates

V validates

Potential Violation of the Serial Order

Transactions T and U such that

U has validated START(T) < FIN(U) RS(T) WS(U) is not empty


T reads X U writes X

U start

T start

U validated

T validating

59

Another Potential Violation of the Serial Order

Two transactions T and U such that

U is in VAL VAL(T) < FIN(U) WS(T) WS(U) is not empty


T writes X
U writes X

U validated

T validating

U finish

60

Validation Rules To validate a transaction T, 1. Check that RS(T) WS(U) is an empty set for any validated U and START(T) < FIN(U) 2. Check that WS(T) WS(U) is an empty set for any validated U that did not finish before T validated, i.e., if VAL(T) < FIN(U)

61

Example
RS = {B} WS= {D} U

RS = {A,D} WS= {A,C}


W

= start
T RS={A,B} WS= {A,C}

V RS={B} WS= {D,E}

= validate = finish
62

Comparison of Three Mechanisms

Storage utilization Locks: space in the lock table is proportional to the number of database elements locked Timestamps: Read and write times for recently accessed database elements Validation: timestamps and read/write sets for each active transaction, plus a few more transactions that finished after some currently active transaction started
63

Comparison of Three Mechanisms


Delay

Locking delays transactions but avoids rollbacks, even when interaction is high If interference is low, neither timestamps nor validation will cause many transactions abort When a rollback is necessary, timestamps catch some problems earlier than validation

64

Вам также может понравиться