4_TranscationManagement

Post on 22-Aug-2014

118 views 2 download

Tags:

Transcript of 4_TranscationManagement

1

Transaction Management

Concurrrency Control

Pearson Education © 2009

Connolly & Begg.

2

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 non-database processing in between.

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

3

Example Transaction

4

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.

5

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.

6

DBMS Transaction Subsystem

7

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.

8

Need for Concurrency Control

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

9

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.

10

Lost Update Problem

T2’s update is lost ! This can be avoided by preventing T1 from reading

balx until after update.

11

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.

12

Uncommitted Dependency Problem

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

13

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).

14

Inconsistent Analysis Problem

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

15

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.

16

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.

17

Example of Conflict Serializability

18

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

19

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.

20

Example - Non-conflict serializable schedule

21

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.

22

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.

23

Example - View Serializable schedule

Exercise

Consider the following schedule

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

24

25

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.

Exercise 2

Consider the following schedule

Determine if the schedule is:• conflict serialisable• view serialisable• recoverable

26

How can the DBMS ensure serializability?

27

28

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.

29

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.

30

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.

31

Preventing Lost Update Problem using 2PL

32

Preventing Uncommitted Dependency Problem using 2PL

33

Preventing Inconsistent Analysis Problem using 2PL

2PL doesn’t solve every potential problem.

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

W(B)

T1 T2

T1 commits

Now T2 aborts!

We should never have let T1 commit.

Cascading rollback34

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

Serializable Schedules

Conflict-serializableSchedules

Two-PhaseLocking

36

37

Deadlock

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

38

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.

39

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.

40

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).

41

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.

42

Example - Wait-For-Graph (WFG)

43

Recovery from Deadlock Detection

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

Exercise

Consider the following schedule involving three transactions T1, T2 and T3:

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

Time T1 T2 T31   W(A)  2   R(B)  3   R(C)  4     W(B)5   W(C)  6     W(C)7   Commit  8 W(B)    9 W(C)    10     R(A)11 Commit    12     Commit

Exercise

Consider the same schedule involving three transactions T1, T2 and T3:

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

Time T1 T2 T31   W(A)  2   R(B)  3   R(C)  4     W(B)5   W(C)  6     W(C)7   Commit  8 W(B)    9 W(C)    10     R(A)11 Commit    12     Commit

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

47

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.

48

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.

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

T starts U starts V starts

Actualschedule

T starts U starts V starts

Serialschedule

50

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))

51

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.

Example

T1 T2 T3 A B C200 150 175 RT=0 RT=0 RT=0

WT=0 WT=0 WT=0

r1(B)

w1(B)w1(A)

r2(A)

w2(C)Abort;

r3(c)

w3(A)

RT=150RT=200

RT=175

WT=200WT=200

WT=175

Transactions Database elements

Writing too late!

52

Timestamps vs. Locks

Time stamps

• Superior if– most transactions are read-only– rare that concurrent transactions

will read or write the same element

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

Locks

• Superior in high-conflict situations

• Frequently delay transactions as they wait for locks

53

54

Comparison of Methods

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 T’s– 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

T validates U validates V validates

Actualschedule

Serialschedule

T validates U validates V validates58

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

U start T start U validated T validating

T reads XU writes X

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 validating U finish

T writes XU writes X

U validated 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

U

RS = {B}WS= {D}

TRS={A,B}WS= {A,C}

W

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

VRS={B}WS= {D,E}

= start= 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