제16장 동시성 제어 Concurrency Control

72
제 16 제 제제제 제제 Concurrency Control 제제제제제제제제제제제제제 제제제제제제제제제제제제제 제제제제제제제제제제 제제제제제제제제제제 제제제제제 제제제제제 소소소소소소소소 소소소소소소소소 소소소소 소소소소

description

소프트디콘사업단. NURI. 산학협동. Soft-Dicon. 제16장 동시성 제어 Concurrency Control. 데이터베이스및웹공학연구실 컴퓨터멀티미디어학부 동국대학교. 록 기반 규약( Lock-Based Protocols) 타임스탬프 기반 규약( Timestamp-Based Protocols) 검증 기반 규약( Validation-Based Protocols) 다중 세분도( Multiple Granularity) 다중 버전 기법( Multiversion Schemes) - PowerPoint PPT Presentation

Transcript of 제16장 동시성 제어 Concurrency Control

Page 1: 제16장 동시성 제어 Concurrency Control

제 16 장 동시성 제어Concurrency Control

데이터베이스및웹공학연구실데이터베이스및웹공학연구실컴퓨터멀티미디어학부컴퓨터멀티미디어학부

동국대학교동국대학교

소프트디콘사업단소프트디콘사업단산학협동산학협동

Page 2: 제16장 동시성 제어 Concurrency Control

목차록 기반 규약 (Lock-Based Protocols)타임스탬프 기반 규약 (Timestamp-Based

Protocols)검증 기반 규약 (Validation-Based Protocols)다중 세분도 (Multiple Granularity)다중 버전 기법 (Multiversion Schemes)교착상태 처리 (Deadlock Handling)삽입 삭제 연산 (Insert and Delete

Operations)약한 수준의 일관성색인구조에서 동시성 (Concurrency in Index

Structures)

Page 3: 제16장 동시성 제어 Concurrency Control

잠금 (lock) 기반 규약잠금 ( 롴 ) 은 자료항목에 동시접근을 제어하기 위한

장치 A lock is a mechanism to control concurrent access

to a data item. 상호 배타적 접근 방법 : 자료의 잠금을 가진

트랜잭션만 접근 허용▪ Ti: 트랜잭션 , Q: 데이터 항목

공유 - 잠금방식 (shared (S) mode): Ti 가 Q 에 공유 잠금 ( 록 -S ) 방식을 가지고 있다면 Ti 는 Q 를 읽을 수는 있지만 갱신할 수는 없다 .

배타 - 잠금 방식 (exclusive (X) mode): Ti 가 Q 에 배타적 잠금 ( 록 -X) 방식을 가지고 있다면 Ti 는 Q 를 읽을 수도 있고 갱신할 수도 있다 .

잠금 요청은 동시성 제어 관리기 에게 하며 , 잠금이 부여된 이후에만 트랜잭션은 자료 항목 Q 를 처리 가능 .

QTilock

access

Page 4: 제16장 동시성 제어 Concurrency Control

잠금 기반 규약 ( 계속 )• 잠금 호환성 행렬 (Lock-compatibility matrix)

• 공유방식 잠금는 공유방식 잠금와 호환성을 갖지만 배타방식 잠금과는 호환성을 갖지 않는다 . 배타적 잠금을 걸려면 해당 항목에 걸려 있는 모든 공유잠금이 풀려야 가능하다 .

• 어떤 수의 트랜잭션은 한 항목에 관하여 공유 잠금을 가질 수 있지만 , 어떤 트랜잭션이 배타적 잠금을 가진다면 , 어떤 다른 트랜잭션도 항목에 대하여 어떠한 잠금도 가질 수 없다 .

• 어떤 잠금이 부여될 수 없다면 , 요청하는 트랜잭션은 다른 트랜잭션이 가진 비호환 잠금들이 풀릴 때까지 기다려야 한다 . 그 때 잠금이 다시 부여된다 .

Ti

Tj Q

Ti Tj

Page 5: 제16장 동시성 제어 Concurrency Control

잠금 기반 규약 ( 계속 ) • 잠금 (locking) 을 이행하는 트랜잭션의 예 :

• 위와같이 잠금은 직렬성을 보장하기에 충분하지 않다 . A 와 B 는 A 와 B의 읽기 사이에서 갱신되면 표현된 합은 틀리게 된다 .

• 그림 16.4 에서 오류발생 이유 : T2 가 비일관성 상태의 자료 접근• 그림 16.5, 16.6(562 쪽 ) 은 오류를 발생시키지 않는다 .• 로킹규약 (locking protocol) 은 자료 항목에 록을 걸거나 푸는 때를 알려

준다 . 로킹 규약은 실행 가능한 스케줄의 수를 제한한다 .• 여기서 충돌 직렬성을 갖는 로킹 규약만을 다룬다 .

T2: lock-S(A); read (A); unlock(A);

lock-S(B); read (B); unlock(B); display(A+B)

T1: lock-X(B); read (B); B:= B - 50; write(B); unlock(B); lock-X(A); read(A); A:= A+50; write(A); unlock(A);

-50

+50

B

A

Page 6: 제16장 동시성 제어 Concurrency Control

참고 : 충돌 직렬성 (Cont.)스케줄 S 가 일련의 비충돌 명령어의 교환에

의하여 스케줄 S´ 으로 변환될 수 있다면 , S 와 S´ 는 충돌동등 ( conflict equivalent) 라 한다 .

스케줄 S 가 직렬스케줄과 충돌동등이라면 , 그 스케줄은 충돌직렬가능 ( 적 )(conflict serializable) 이라 한다 . 스케줄 3 => 스케줄 5

▪ T1 read(B)T2 read(A)▪ T1 write(B)T2 write(A)▪ T1 write(B)T2 read(A)

순서변경을 모두 변경하면 => 스케줄 6

T1 T2

Read(A)Write(A)Read(B)write(B) Read(A)

Write(A)Read(B)Write(B)

T1 T2

Read(A)Write(A)

Read(B)

write(B)

Read(A)

Write(A)

Read(B)Write(B)

스케줄 6스케줄 5

Page 7: 제16장 동시성 제어 Concurrency Control

잠금 기반 규약 ( 계속 ) 부분 스케줄을 고려하라 :

교착상태 (deadlock) T3 와 T4 모두 더 이상 진행할 수 없음 lock-S(B) 을 수행하는 것은 T4 는 T3 가 B 에 관한 록을 푸는

것을 기다리게 하며 , 반면에 lock-X(A) 를 수행하는 것은 T3 가 T4 로 하여금 A 에 관한 록을 푸는 것을 기다리게 한다 .

교착상태를 해결하려면 T3 또는 T4 가운데 하나는 취소되어야 한하며 , 각각의 록을 풀어주어야 한다 .

교착상태의 잠재성은 잠금규약에 존재 . 한편으로 필요의 악

A B

T3 T4

XSX S

Page 8: 제16장 동시성 제어 Concurrency Control

롴 ( 잠금 ) 기반 규약 ( 계속 ) 스케줄 S 에 포함된 트랜잭션 : {T0,T1,T2,…,Tn} Ti 가 Q 에 모드 A 록을 가지고 , Tj 가 Q 에 모드 B 록을

가지면서 comp(A,B)=false 인 Q 가 있을 경우 , (563 쪽 수정 )

스케줄 S 에서 Ti 가 Tj 를 앞서고 , Ti -> Tj 로 표기 . 동등한 연산순서를 가진 모든 스케줄에서 Ti 가 Tj 를 앞서야 함 스케줄 S 가 로킹규약을 따르는 트랜잭션들의 스케줄이라면 주어진

로킹규약 아래서 S 는 정당하다 고 할 수 있다 . 모든 정당한 스케줄들이 충돌직렬성을 가진다면 충돌직렬성을

보장한다 고 할 수 있다 .

lock A lock B1 2

QTi Tj

Page 9: 제16장 동시성 제어 Concurrency Control

록의 허용 Starvation( 기아상태 ) is also possible if concurrency

control manager is badly designed.(p610) A transaction may be waiting for an X-lock on an item, while

a sequence of other transactions request and are granted an S-lock on the same item. It may not grant X-lock.

동시성 제어 관리기의 기아상태 방지 설계 : Ti 가 M 모드로 Q에 요청할 경우 , 두 경우에만 록 허용 Q 에 걸려 있는 록 모드 가운데 M 과 충돌하는 트랜잭션이 없음 Ti 보다 먼저 Q 에 록을 요청해서 기다리고 있는 트랜잭션이 없음

QT2S-lock

T1

T3S-lock

X-lock

123

? 불가

배고파 죽겠네 !T4 s-lock4

Page 10: 제16장 동시성 제어 Concurrency Control

2 단계 잠금 규약2 단계 잠금 (2PL:two phase locking) 규약은

충돌 직렬가능 스케줄을 보장하는 규약이다 . Phase 1: Growing Phase

transaction may obtain locks transaction may not release locks

Phase 2: Shrinking Phase transaction may release locks transaction may not obtain locks

2PL 규약은 충돌 직렬성 즉 직렬가능성을 보장한다 . 트랜잭션들은 록 종점 (lock point) 의 순서로 직렬화될 수 있다는 것이 증명될 수 있다 . ( 즉 어떤 트랜잭션이 마지막 록을 얻은 지점 ).

록(lock)

단계 1:증가단계

단계 2:감소단계

록 종점

lock unlock

Page 11: 제16장 동시성 제어 Concurrency Control

2 단계 잠금규약 (Cont.)2 단계 로킹은 교착상태 (deadlock) 가 없음을

보장하지 못한다 .연쇄취소는 2PL 에서 가능 . 2 가지 회피 방안

엄격한 2 단계로킹 (strict two-phase locking) 규약 . 트랜잭션이 완료되거나 취소될 때까지 모든 배타적 록 유지함

엄밀한 2 단계로킹 (Rigorous two-phase locking) 엄격한 2PL 보다 더 엄격 모든 록들이 완료 또는 취소될 때까지 유지된다 . 따라서 , 트랜잭션은 그들이 완료하는 순서로 직렬화될 수

있다 .

Page 12: 제16장 동시성 제어 Concurrency Control

2 단계 잠금규약 (Cont.)• 어떤 트랜잭션에는 2PL 규약으로는 얻을 수

없는 충돌직렬가능 스케줄이 있을 수 있다 . – 2PL 이 아닌 충돌직렬성을 얻으려면 부가 정보

필요 ( 예 , 자료에 접근하는 순서 )– 부가 정보가 없다면 2PL 은 충돌직렬성을 위한

필수요소이다 .– Ti 는 2PL 규약을 따르지 않고 , Tj 는 2PL 을 따를

때 충돌 직렬가능하지 않는 Ti 와 Tj 트랜잭션의 스케줄은 충돌 직렬적이지 않은 스케줄이다 .

Page 13: 제16장 동시성 제어 Concurrency Control

잠금 변환 (Lock Conversions)• Two-phase locking with lock conversions:

– First Phase: – can acquire a lock-S on item– can acquire a lock-X on item– can convert a lock-S to a lock-X (upgrade)

– Second Phase:– can release a lock-S– can release a lock-X– can convert a lock-X to a lock-S (downgrade)

• This protocol assures serializability. But still relies on the programmer to insert the various locking instructions.

Page 14: 제16장 동시성 제어 Concurrency Control

Automatic Acquisition of Locks• A transaction Ti issues the standard read/write instruction,

without explicit locking calls.• The operation read(D) is processed as: if Ti has a lock on D then read(D) else begin if necessary wait until no other transaction has a lock-X on D grant Ti a lock-S on D; read(D) end

Page 15: 제16장 동시성 제어 Concurrency Control

Automatic Acquisition of Locks (Cont.)

• write(D) is processed as: if Ti has a lock-X on D then write(D) else begin if necessary wait until no other Ti has any lock on D, if Ti has a lock-S on D then upgrade lock on D to lock-X else grant Ti a lock-X on D write(D) end;• All locks are released after commit or abort

Page 16: 제16장 동시성 제어 Concurrency Control

로킹의 구현 (Implementation of Locking)

록 관리기 (Lock manager) 는 트랜잭션이 잠금 , 해제 요청을 보내는 별도의 프로세서로 구현될 수 있음

The lock manager replies to a lock request by sending a lock grant messages (or a message asking the transaction to roll back, in case of a deadlock)

The requesting transaction waits until its request is answered

The lock manager maintains a data structure called a lock table to record granted locks and pending requests( 요청 미결 )

The lock table is usually implemented as an in-memory hash table indexed on the name of the data item being locked

Page 17: 제16장 동시성 제어 Concurrency Control

잠금표 (Lock Table) 검은색 사각형은 잠금을 부여 받았음을

나타내고 , 흰 것은 대기 요청을 나타냄 잠금표는 또한 부여되거나 요청된

잠금의 형태를 기록함 새로운 요청은 해당 자료 항목에 대한

요청들의 줄 끝에 추가된다 . 모든 선행 잠금들과 호환이면 부여된다 .

Unlock requests result in the request being deleted, and later requests are checked to see if they can now be granted

If transaction aborts, all waiting or granted requests of the transaction are deleted lock manager may keep a list of

locks held by each transaction, to implement this efficiently

Page 18: 제16장 동시성 제어 Concurrency Control

그래프 기반 규약 (Graph-Based Protocols)

( 교재 568 쪽 )Graph-based protocols are an alternative

to two-phase locking접근되는 자료항목의 순서에 대한 정보

Impose a partial ordering on the set D = {d1, d2 ,..., dh} of all data items.

If di dj then any transaction accessing both di and dj must access di before accessing dj.

Implies that the set D may now be viewed as a directed acyclic graph, called a database graph.

Page 19: 제16장 동시성 제어 Concurrency Control

Tree Protocol• 트리규약 (tree-protocol ): 그래프

규약의 일종 ,lock-X 만 허용1. 트랜잭션의 첫번째 잠금은 어떤 자료

항목에도 걸릴 수 있음2. 그 후 계속해서 자료 Q 는 Ti 에

의하여 잠길 수 있다 . 단 , Q 의 부모 노드는 현재 Ti 에 의하여 잠겨있다 .

3. 자료항목들은 언제라도 풀릴 수 있다 .

4. Ti 에 의해 잠금이 걸렸다 풀린 자료 항목은 또 다시 Ti 에 의하여 잠금이 걸릴 수 없다 .

Page 20: 제16장 동시성 제어 Concurrency Control

Graph-Based Protocols (Cont.)

• The tree protocol ensures conflict serializability as well as freedom from deadlock.

• Unlocking may occur earlier Unlocking may occur earlier in the tree-locking protocol than in the two-phase locking protocol.– shorter waiting times, and increase in concurrency– protocol is deadlock-free, no rollbacks are required– the abort of a transaction can still lead to cascading rollbacks. (this correction has to be made in the book also.)

• However, in the tree-locking protocol, a transaction may have to lock data items that it does not access.– increased locking overhead, and additional waiting time– potential decrease in concurrency

• Schedules not possible under two-phase locking are possible under tree protocol, and vice versa.

Page 21: 제16장 동시성 제어 Concurrency Control

타임스탬프 기반 규약 (Timestamp-Based Protocols)

• 각 트랜잭션은 시스템에 들어가면 시간도장 (TS: timestamp)을 받는다 . – 먼저 들어온 트랜잭션 Ti 의 시간도장 TS(Ti)

– 새로운 트랜잭션 Tj 의 시간도장 TS(Tj)

– 둘의 관계는 TS(Ti) <TS(Tj)

• 시간도장 규약은 병행 ( 동시 ) 실행을 관리하는데 , 여기서 시간도장은 직렬순서를 결정한다 .

• 그러한 행위를 보장하기 위하여 규약은 각 자료 Q 에 대하여 두개의 시간도장 값을 유지함 :– W-timestamp(Q) is the largest time-stamp of any transaction that

executed write(Q) successfully.– R-timestamp(Q) is the largest time-stamp of any transaction that

executed read(Q) successfully.

Page 22: 제16장 동시성 제어 Concurrency Control

Timestamp-Based Protocols (Cont.)

• 시간도장 순서규약에서 어떤 충돌 읽기 ,쓰기 연산은 시간도장순으로 실행됨을 보장함 .

• Suppose a transaction Ti issues a read(Q)– TS(Ti) < TS(Tj) 1. If TS(Ti) W-timestamp(Q), then Ti needs to read a value of Q that

was already overwritten. Hence, the read operation is rejected, and Ti is rolled back. ( 후배가 쓴 것을 읽을 수 없음 )

2. If TS(Ti) W-timestamp(Q), then the read operation is executed, and R-timestamp(Q) is set to the maximum of R-timestamp(Q) and TS(Ti).

(선배가 쓴 것은 읽을 수 있음 )

QW-

timestampR-timestamp

TiTj

Page 23: 제16장 동시성 제어 Concurrency Control

Timestamp-Based Protocols (Cont.)

• Suppose that transaction Ti issues write(Q).– a. If TS(Ti) < R-timestamp(Q), then the value of Q that Ti

is producing was needed previously, and the system assumed that that value would never be produced. Hence, the write operation is rejected, and Ti is rolled back.

• 후배가 읽은 후 선배가 쓸 수 없음

– b. If TS(Ti) < W-timestamp(Q), then Ti is attempting to write an obsolete value of Q. Hence, this write operation is rejected, and Ti is rolled back.

• 후배가 쓴 다음에 선배가 쓸 수 없음 . • 토마스의 기록규칙은 Ti 의 복귀 (abort) 필요 없음을 밝힘 .

– c. Otherwise, the write operation is executed, and W-timestamp(Q) is set to TS(Ti).

Page 24: 제16장 동시성 제어 Concurrency Control

Example Use of the ProtocolA partial schedule for several data items for

transactions with timestamps 1, 2, 3, 4, 5

T1 T2 T3 T4 T5

read(Y)read(X)

read(Y)write(Y) write(Z)

read(Z) read(X) abort read(X)

write(Z) abort

write(Y) write(Z)

Page 25: 제16장 동시성 제어 Concurrency Control

Correctness of Timestamp-Ordering Protocol

• (572 쪽 ) • 시간도장 순서규약은 직렬성을 보장한다 . 그것은

연산들이시간도장 순서에 따라 처리되기 때문이다 .• 이 규약은 교착상태도 해결한다 . 이유는 대기상태에 있는

트랜잭션이 없기 때문이다 . 짧은 트랜잭션과 충돌로 긴 트랜잭션이 계속 재시작할 경우 기아상태기아상태가 발생할 수 있다 .

• 복구가능한 스케줄을 생성할 수도 있다 .

transactionwith smallertimestamp

transactionwith largertimestamp

Page 26: 제16장 동시성 제어 Concurrency Control

• Problem with timestamp-ordering protocol:– Suppose Ti aborts, but Tj has read a data item written by Ti

– Then Tj must abort; if Tj had been allowed to commit earlier, the schedule is not recoverable.

– Further, any transaction that has read a data item written by Tj must abort

– This can lead to cascading rollback --- that is, a chain of rollbacks

• Solution:– A transaction is structured such that its writes are all performed

at the end of its processing– All writes of a transaction form an atomic action; no transaction

may execute while a transaction is being written– A transaction that is aborted is restarted with a new timestamp

Recoverability and Cascade Freedom

Page 27: 제16장 동시성 제어 Concurrency Control

Thomas’Write Rule• Modified version of the timestamp-ordering protocol in which

obsolete write operations may be ignored under certain circumstances.

• When Ti attempts to write data item Q, if TS(Ti) < W-timestamp(Q), then Ti is attempting to write an obsolete value of {Q}. Hence, rather than rolling back Ti as the timestamp ordering protocol would have done, this {write} operation can be ignored.

• Otherwise this protocol is the same as the timestamp ordering protocol.

• Thomas' Write Rule allows greater potential concurrency. Unlike previous protocols, it allows some view-serializable schedules that are not conflict-serializable.

Page 28: 제16장 동시성 제어 Concurrency Control

검증기반규약 (Validation-Based Protocol)

• Execution of transaction Ti is done in three phases.– 1. Read and execution phase: Transaction Ti writes only to

temporary local variables– 2. Validation phase: Transaction Ti performs a “validation test” to

determine if local variables can be written without violating serializability.

– 3. Write phase: If Ti is validated, the updates are applied to the database; otherwise, Ti is rolled back.

• The three phases of concurrently executing transactions can be interleaved, but each transaction must go through the three phases in that order.

• Also called as optimistic concurrency control since transaction executes fully in the hope that all will go well during validation

Page 29: 제16장 동시성 제어 Concurrency Control

Validation-Based Protocol (Cont.)

• Each transaction Ti has 3 timestamps– Start(Ti) : the time when Ti started its execution

– Validation(Ti): the time when Ti entered its validation phase

– Finish(Ti) : the time when Ti finished its write phase

• Serializability order is determined by timestamp given at validation time, to increase concurrency. Thus TS(Ti) is given the value of Validation(Ti).

• This protocol is useful and gives greater degree of concurrency if probability of conflicts is low. That is because the serializability order is not pre-decided and relatively less transactions will have to be rolled back.

Page 30: 제16장 동시성 제어 Concurrency Control

Validation Test for Transaction Tj

• If for all Ti with TS (Ti) < TS (Tj) either one of the following condition holds:– finish(Ti) < start(Tj) – start(Tj) < finish(Ti) < validation(Tj) and the set of data items written by Ti does

not intersect with the set of data items read by Tj.

then validation succeeds and Tj can be committed. Otherwise, validation fails and Tj is aborted.

• Justification: Either first condition is satisfied, and there is no overlapped execution, or second condition is satisfied and

1. the writes of Tj do not affect reads of Ti since they occur after Ti has finished its reads. 2. the writes of Ti do not affect reads of Tj since Tj does not read any item written by Ti.

start(Ti)

finish(Ti)

start(Tj)

start(Ti) finish(Ti)

start(Tj) validation(Tj

)

finish(Tj)

Page 31: 제16장 동시성 제어 Concurrency Control

Schedule Produced by Validation

• Example of schedule produced using validation

T14 T15

read(B)read(B)B:- B-50read(A)A:- A+50

read(A)(validate)display (A+B)

(validate)write (B)write (A)

Page 32: 제16장 동시성 제어 Concurrency Control

Multiple Granularity• (575 쪽 )• Allow data items to be of various sizes and define a hierarchy

of data granularities, where the small granularities are nested within larger ones– 잠금을 거는 단위는 무엇을 할 것인가 ?– Can be represented graphically as a tree (but don't confuse with tree-

locking protocol)

• When a transaction locks a node in the tree explicitly, it implicitly locks all the node's descendents in the same mode.

• Granularity of locking (level in tree where locking is done):– fine granularity (lower in tree): high concurrency, high locking overhead– coarse granularity (higher in tree): low locking overhead, low

concurrency

Page 33: 제16장 동시성 제어 Concurrency Control

Example of Granularity Hierarchy

The highest level in the example hierarchy is the entire database.

The levels below are of type area, file and record in that order.

Page 34: 제16장 동시성 제어 Concurrency Control

Intention Lock Modes• In addition to S and X lock modes, there are three

additional lock modes with multiple granularity:– intention-shared (IS): indicates explicit locking at a lower

level of the tree but only with shared locks.– intention-exclusive (IX): indicates explicit locking at a

lower level with exclusive or shared locks– shared and intention-exclusive (SIX): the subtree rooted

by that node is locked explicitly in shared mode and explicit locking is being done at a lower level with exclusive-mode locks.

• intention locks allow a higher level node to be locked in S or X mode without having to check all descendent nodes.

Page 35: 제16장 동시성 제어 Concurrency Control

Compatibility Matrix with Intention Lock Modes

• The compatibility matrix for all lock modes is:

IS IX S S IX X

IS

IX

S

S IX

X

Page 36: 제16장 동시성 제어 Concurrency Control

Multiple Granularity Locking Scheme

• Transaction Ti can lock a node Q, using the following rules:– 1. The lock compatibility matrix must be observed.– 2. The root of the tree must be locked first, and may be locked in

any mode.– 3. A node Q can be locked by Ti in S or IS mode only if the parent

of Q is currently locked by Ti in either IX or IS mode.– 4. A node Q can be locked by Ti in X, SIX, or IX mode only if the

parent of Q is currently locked by Ti in either IX or SIX mode.– 5. Ti can lock a node only if it has not previously unlocked any

node (that is, Ti is two-phase).– 6. Ti can unlock a node Q only if none of the children of Q are

currently locked by Ti.• Observe that locks are acquired in root-to-leaf order,

whereas they are released in leaf-to-root order.

Page 37: 제16장 동시성 제어 Concurrency Control

Multiversion Schemes• Multiversion schemes keep old versions of data

item to increase concurrency.– Multiversion Timestamp Ordering– Multiversion Two-Phase Locking

• Each successful write results in the creation of a new version of the data item written.

• Use timestamps to label versions.• When a read(Q) operation is issued, select an

appropriate version of Q based on the timestamp of the transaction, and return the value of the selected version.

• reads never have to wait as an appropriate version is returned immediately.

Page 38: 제16장 동시성 제어 Concurrency Control

Multiversion Timestamp Ordering

• Each data item Q has a sequence of versions <Q1, Q2,...., Qm>. Each version Qk contains three data fields:– Content -- the value of version Qk.– W-timestamp(Qk) -- timestamp of the transaction that created

(wrote) version Qk

– R-timestamp(Qk) -- largest timestamp of a transaction that successfully read version Qk

• when a transaction Ti creates a new version Qk of Q, Qk's W-timestamp and R-timestamp are initialized to TS(Ti).

• R-timestamp of Qk is updated whenever a transaction Tj reads Qk, and TS(Tj) > R-timestamp(Qk).

Page 39: 제16장 동시성 제어 Concurrency Control

Multiversion Timestamp Ordering (Cont)

• The multiversion timestamp scheme presented next ensures serializability.

• Suppose that transaction Ti issues a read(Q) or write(Q) operation. Let Qk denote the version of Q whose write timestamp is the largest write timestamp less than or equal to TS(Ti).– 1. If transaction Ti issues a read(Q), then the value returned is the content

of version Qk.

– 2. If transaction Ti issues a write(Q), and if TS(Ti) < R-timestamp(Qk), then transaction Ti is rolled back. Otherwise, if TS(Ti) = W-timestamp(Qk), the contents of Qk are overwritten, otherwise a new version of Q is created.

• Reads always succeed; a write by Ti is rejected if some other transaction Tj that (in the serialization order defined by the timestamp values) should read Ti's write, has already read a version created by a transaction older than Ti.

Page 40: 제16장 동시성 제어 Concurrency Control

Multiversion Two-Phase Locking• Differentiates between read-only transactions and update

transactions• Update transactions acquire read and write locks, and hold

all locks up to the end of the transaction. That is, update transactions follow rigorous two-phase locking.– Each successful write results in the creation of a new version of the

data item written.– each version of a data item has a single timestamp whose value is

obtained from a counter ts-counter that is incremented during commit processing.

• Read-only transactions are assigned a timestamp by reading the current value of ts-counter before they start execution; they follow the multiversion timestamp-ordering protocol for performing reads.

Page 41: 제16장 동시성 제어 Concurrency Control

Multiversion Two-Phase Locking (Cont.)• When an update transaction wants to read a data item, it

obtains a shared lock on it, and reads the latest version. • When it wants to write an item, it obtains X lock on; it then

creates a new version of the item and sets this version's timestamp to .

• When update transaction Ti completes, commit processing occurs:– Ti sets timestamp on the versions it has created to ts-counter + 1– Ti increments ts-counter by 1

• Read-only transactions that start after Ti increments ts-counter will see the values updated by Ti.

• Read-only transactions that start before Ti increments thets-counter will see the value before the updates by Ti.

• Only serializable schedules are produced.

Page 42: 제16장 동시성 제어 Concurrency Control

교착상태처리 (Deadlock Handling)

• Consider the following two transactions: T1: write (X) T2: write(Y) write(Y) write(X)• Schedule with deadlock

T1 T2

lock-X on Xwrite (X)

lock-X on Ywrite (X) wait for lock-X on X

wait for lock-X on Y

Page 43: 제16장 동시성 제어 Concurrency Control

Deadlock Handling• System is deadlocked if there is a set of

transactions such that every transaction in the set is waiting for another transaction in the set.

• Deadlock prevention protocols ensure that the system will never enter into a deadlock state.

• Some prevention strategies :– Require that each transaction locks all its data items

before it begins execution (predeclaration).– Impose partial ordering of all data items and require that

a transaction can lock data items only in the order specified by the partial order (graph-based protocol).

Page 44: 제16장 동시성 제어 Concurrency Control

More Deadlock Prevention Strategies

• Following schemes use transaction timestamps for the sake of deadlock prevention alone.

• wait-die scheme — non-preemptive– older transaction may wait for younger one to release data

item. Younger transactions never wait for older ones; they are rolled back instead.

– a transaction may die several times before acquiring needed data item

• wound-wait scheme — preemptive– older transaction wounds (forces rollback) of younger

transaction instead of waiting for it. Younger transactions may wait for older ones.

– may be fewer rollbacks than wait-die scheme.

Page 45: 제16장 동시성 제어 Concurrency Control

Deadlock prevention (Cont.)• Both in wait-die and in wound-wait schemes, a

rolled back transactions is restarted with its original timestamp. Older transactions thus have precedence over newer ones, and starvation is hence avoided.

• Timeout-Based Schemes :– a transaction waits for a lock only for a specified amount

of time. After that, the wait times out and the transaction is rolled back.

– thus deadlocks are not possible– simple to implement; but starvation is possible. Also

difficult to determine good value of the timeout interval.

Page 46: 제16장 동시성 제어 Concurrency Control

Deadlock Detection• Deadlocks can be described as a wait-for graph, which

consists of a pair G = (V,E), – V is a set of vertices (all the transactions in the system)– E is a set of edges; each element is an ordered pair Ti Tj.

• If Ti Tj is in E, then there is a directed edge from Ti to Tj, implying that Ti is waiting for Tj to release a data item.

• When Ti requests a data item currently being held by Tj, then the edge Ti Tj is inserted in the wait-for graph. This edge is removed only when Tj is no longer holding a data item needed by Ti.

• The system is in a deadlock state if and only if the wait-for graph has a cycle. Must invoke a deadlock-detection algorithm periodically to look for cycles.

Page 47: 제16장 동시성 제어 Concurrency Control

Deadlock Detection (Cont.)

Wait-for graph without a cycle Wait-for graph with a cycle

Page 48: 제16장 동시성 제어 Concurrency Control

Deadlock Recovery• When deadlock is detected :

– Some transaction will have to rolled back (made a victim) to break deadlock. Select that transaction as victim that will incur minimum cost.

– Rollback -- determine how far to roll back transaction

• Total rollback: Abort the transaction and then restart it.• More effective to roll back transaction only as far as necessary to break

deadlock.

– Starvation happens if same transaction is always chosen as victim. Include the number of rollbacks in the cost factor to avoid starvation

Page 49: 제16장 동시성 제어 Concurrency Control

Insert and Delete Operations

• If two-phase locking is used :– A delete operation may be performed only if the transaction deleting

the tuple has an exclusive lock on the tuple to be deleted.– A transaction that inserts a new tuple into the database is given an X-

mode lock on the tuple• Insertions and deletions can lead to the phantom

phenomenon.– A transaction that scans a relation (e.g., find all accounts in

Perryridge) and a transaction that inserts a tuple in the relation (e.g., insert a new account at Perryridge) may conflict in spite of not accessing any tuple in common.

– If only tuple locks are used, non-serializable schedules can result: the scan transaction may not see the new account, yet may be serialized before the insert transaction.

Page 50: 제16장 동시성 제어 Concurrency Control

Insert and Delete Operations (Cont.)

• The transaction scanning the relation is reading information that indicates what tuples the relation contains, while a transaction inserting a tuple updates the same information.– The information should be locked.

• One solution: – Associate a data item with the relation, to represent the information about

what tuples the relation contains.– Transactions scanning the relation acquire a shared lock in the data item, – Transactions inserting or deleting a tuple acquire an exclusive lock on the

data item. (Note: locks on the data item do not conflict with locks on individual tuples.)

• Above protocol provides very low concurrency for insertions/deletions.• Index locking protocols provide higher concurrency while

preventing the phantom phenomenon, by requiring locks on certain index buckets.

Page 51: 제16장 동시성 제어 Concurrency Control

Index Locking Protocol• Every relation must have at least one index. Access to a

relation must be made only through one of the indices on the relation.

• A transaction Ti that performs a lookup must lock all the index buckets that it accesses, in S-mode.

• A transaction Ti may not insert a tuple ti into a relation r without updating all indices to r.

• Ti must perform a lookup on every index to find all index buckets that could have possibly contained a pointer to tuple ti, had it existed already, and obtain locks in X-mode on all these index buckets. Ti must also obtain locks in X-mode on all index buckets that it modifies.

• The rules of the two-phase locking protocol must be observed.

Page 52: 제16장 동시성 제어 Concurrency Control

약한 수준의 일관성 (Weak Levels of Consistency)

• 2 단계 일관성 (Degree-two consistency): 2 단계 로킹에서 S- 록 들은 아무 때에 해제될 수 있고 , 획득될 수 있다는 점과는 다르다 .– X- 록은 트랜잭션이 끝날 때가지 유지되어야 한다 .– 직렬성은 보장되지 않지만 , 프로그래머는 오류성

데이터베이스가 결코 일어나지 않을 것이라는 것을 보장해야 한다 .

• 커서 안정성 (Cursor stability): – 릴레이션의 투플들에 반복적인 작업을 수행하는 호스트 언어로 작성된 프로그램용 설계로서 일종의 2 단계 일관성

– 전체 릴레이션에 록을 거는 대신 커서 안전성의 보장• 읽기를 위하여 , 1) 각 투플을 잠그고 , 2) 읽고 , 3) 록은 즉각적 해제• X- 록들은 트랜잭션이 끝난 후 해제• 2 단계 일관성의 특수한 경우

Page 53: 제16장 동시성 제어 Concurrency Control

SQL 에서 약한 수준 일관성• SQL 은 트랜잭션간 직렬가능하지 않은 수행 허용

– Serializable: 잠정적이다 .– Repeatable read: 단지 완료된 레코드만 읽을 수 있고 ,

한 트랜잭션이 한 레코드를 두 번 읽는 사이에 다른 트랜잭션이 그 트랜잭션을 갱신하지 못하도록 한다 .

• 그러나 트랜잭션들은 직렬가능하지 않을 수 있다 . 그러나 팬텀 현상은 방지될 수 없다 .

– T1 은 T2 에 의하여 삽입된 몇몇 레코드들을 볼 수 있지만 , T2 에 의하여 삽입된 다른 것들은 볼 수 없을 수 있다 .

– Read committed: 완료된 레코드들은 읽을 수 있고 , repeatable read 는 요구되지 않는 것이다 . 2 단계 일관성과 같지만 , 대부분의 시스템들은 커서 안전성으로 그것을 구현한다 .

– Read uncommitted: 완료되지 않은 자료도 읽는다 . SQL-92 에서 허용하는 것 가운데 가장 낮은 수준의 일관성을 제공함 .

Page 54: 제16장 동시성 제어 Concurrency Control

Concurrency in Index Structures

• Indices are unlike other database items in that their only job is to help in accessing data.

• Index-structures are typically accessed very often, much more than other database items.

• Treating index-structures like other database items leads to low concurrency. Two-phase locking on an index may result in transactions executing practically one-at-a-time.

• It is acceptable to have nonserializable concurrent access to an index as long as the accuracy of the index is maintained.

• In particular, the exact values read in an internal node of a B+-tree are irrelevant so long as we land up in the correct leaf node.

• There are index concurrency protocols where locks on internal nodes are released early, and not in a two-phase fashion.

Page 55: 제16장 동시성 제어 Concurrency Control

Concurrency in Index Structures (Cont.)

• Example of index concurrency protocol:• Use crabbing instead of two-phase locking on the nodes of

the B+-tree, as follows. During search/insertion/deletion:– First lock the root node in shared mode.– After locking all required children of a node in shared mode, release

the lock on the node.– During insertion/deletion, upgrade leaf node locks to exclusive

mode.– When splitting or coalescing requires changes to a parent, lock the

parent in exclusive mode.

• Above protocol can cause excessive deadlocks. Better protocols are available; see Section 16.9 for one such protocol, the B-link tree protocol

Page 56: 제16장 동시성 제어 Concurrency Control

End of Chapter

Page 57: 제16장 동시성 제어 Concurrency Control

Partial Schedule Under Two-Phase Locking

Page 58: 제16장 동시성 제어 Concurrency Control

Incomplete Schedule With a Lock Conversion

Page 59: 제16장 동시성 제어 Concurrency Control

Lock Table

Page 60: 제16장 동시성 제어 Concurrency Control

Tree-Structured Database Graph

Page 61: 제16장 동시성 제어 Concurrency Control

Serializable Schedule Under the Tree Protocol

Page 62: 제16장 동시성 제어 Concurrency Control

Schedule 3

Page 63: 제16장 동시성 제어 Concurrency Control

Schedule 4

Page 64: 제16장 동시성 제어 Concurrency Control

Schedule 5, A Schedule Produced by Using Validation

Page 65: 제16장 동시성 제어 Concurrency Control

Granularity Hierarchy

Page 66: 제16장 동시성 제어 Concurrency Control

Compatibility Matrix

Page 67: 제16장 동시성 제어 Concurrency Control

Wait-for Graph With No Cycle

Page 68: 제16장 동시성 제어 Concurrency Control

Wait-for-graph With A Cycle

Page 69: 제16장 동시성 제어 Concurrency Control

Nonserializable Schedule with Degree-Two Consistency

Page 70: 제16장 동시성 제어 Concurrency Control

B+-Tree For account File with n = 3.

Page 71: 제16장 동시성 제어 Concurrency Control

Insertion of “Clearview” Into the B+-Tree of Figure 16.21

Page 72: 제16장 동시성 제어 Concurrency Control

Lock-Compatibility Matrix