1 / 72

제16장 동시성 제어 Concurrency Control

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

aderes
Download Presentation

제16장 동시성 제어 Concurrency Control

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 소프트디콘사업단 NURI 산학협동 Soft-Dicon 제16장 동시성 제어Concurrency Control 데이터베이스및웹공학연구실 컴퓨터멀티미디어학부 동국대학교

  2. 록 기반 규약(Lock-Based Protocols) 타임스탬프 기반 규약(Timestamp-Based Protocols) 검증 기반 규약(Validation-Based Protocols) 다중 세분도(Multiple Granularity) 다중 버전 기법(Multiversion Schemes) 교착상태 처리(Deadlock Handling) 삽입 삭제 연산(Insert and Delete Operations) 약한 수준의 일관성 색인구조에서 동시성(Concurrency in Index Structures) 목차

  3. 잠금(롴)은 자료항목에 동시접근을 제어하기 위한 장치 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를 처리 가능. 잠금(lock)기반 규약 lock Q Ti access

  4. 잠금 호환성 행렬(Lock-compatibility matrix) 공유방식 잠금는 공유방식 잠금와 호환성을 갖지만 배타방식 잠금과는 호환성을 갖지 않는다. 배타적 잠금을 걸려면 해당 항목에 걸려 있는 모든 공유잠금이 풀려야 가능하다. 어떤 수의 트랜잭션은 한 항목에 관하여 공유 잠금을 가질 수 있지만, 어떤 트랜잭션이 배타적 잠금을 가진다면, 어떤 다른 트랜잭션도 항목에 대하여 어떠한 잠금도 가질 수 없다. 어떤 잠금이 부여될 수 없다면, 요청하는 트랜잭션은 다른 트랜잭션이 가진 비호환 잠금들이 풀릴 때까지 기다려야 한다. 그 때 잠금이 다시 부여된다. 잠금 기반 규약(계속) Tj Q Ti Ti Tj

  5. 잠금(locking)을 이행하는 트랜잭션의 예: 위와같이 잠금은 직렬성을 보장하기에 충분하지 않다. A와 B는 A와 B의 읽기 사이에서 갱신되면 표현된 합은 틀리게 된다. 그림 16.4에서 오류발생 이유: T2가 비일관성 상태의 자료 접근 그림 16.5, 16.6(562쪽)은 오류를 발생시키지 않는다. 로킹규약(locking protocol)은 자료 항목에 록을 걸거나 푸는 때를 알려 준다. 로킹 규약은 실행 가능한 스케줄의 수를 제한한다. 여기서 충돌 직렬성을 갖는 로킹 규약만을 다룬다. 잠금 기반 규약(계속) 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); T2: lock-S(A); read (A); unlock(A); lock-S(B); read (B); unlock(B); display(A+B) B -50 A +50

  6. 참고: 충돌 직렬성(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 스케줄 5 스케줄 6

  7. 부분 스케줄을 고려하라: 교착상태(deadlock) T3와 T4모두 더 이상 진행할 수 없음 lock-S(B)을 수행하는 것은 T4 는 T3가 B에 관한 록을 푸는 것을 기다리게 하며, 반면에 lock-X(A)를 수행하는 것은 T3가 T4로 하여금 A에 관한 록을 푸는 것을 기다리게 한다. 교착상태를 해결하려면 T3또는 T4가운데 하나는 취소되어야 한하며, 각각의 록을 풀어주어야 한다. 교착상태의 잠재성은 잠금규약에 존재. 한편으로 필요의 악 잠금 기반 규약(계속) A B S X X S T3 T4

  8. 롴(잠금) 기반 규약 (계속) • 스케줄 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 B Ti Tj Q 2 1

  9. 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에 록을 요청해서 기다리고 있는 트랜잭션이 없음 록의 허용 배고파 죽겠네! T4 T1 s-lock X-lock 4 S-lock 2 T2 ? Q 불가 1 T3 3 S-lock

  10. 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)의 순서로 직렬화될 수 있다는 것이 증명될 수 있다. (즉 어떤 트랜잭션이 마지막 록을 얻은 지점). 2단계 잠금 규약 록 종점 록 (lock) 단계1: 증가단계 단계2: 감소단계 unlock lock

  11. 2단계 로킹은 교착상태(deadlock)가 없음을 보장하지 못한다. 연쇄취소는 2PL에서 가능. 2가지 회피 방안 엄격한 2단계로킹(strict two-phase locking) 규약. 트랜잭션이 완료되거나 취소될 때까지 모든 배타적 록 유지함 엄밀한 2단계로킹(Rigorous two-phase locking) 엄격한 2PL보다 더 엄격 모든 록들이 완료 또는 취소될 때까지 유지된다. 따라서, 트랜잭션은 그들이 완료하는 순서로 직렬화될 수 있다. 2단계 잠금규약(Cont.)

  12. 어떤 트랜잭션에는 2PL 규약으로는 얻을 수 없는 충돌직렬가능 스케줄이 있을 수 있다. 2PL이 아닌 충돌직렬성을 얻으려면 부가 정보 필요 (예, 자료에 접근하는 순서) 부가 정보가 없다면 2PL은 충돌직렬성을 위한 필수요소이다. Ti는 2PL규약을 따르지 않고, Tj는 2PL을 따를 때 충돌 직렬가능하지 않는 Ti와 Tj 트랜잭션의 스케줄은 충돌 직렬적이지 않은 스케줄이다. 2단계 잠금규약(Cont.)

  13. 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. 잠금 변환(Lock Conversions)

  14. 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 Automatic Acquisition of Locks

  15. 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 Automatic Acquisition of Locks (Cont.)

  16. 로킹의 구현(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 tableto 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

  17. 잠금표(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

  18. (교재 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. 그래프 기반 규약(Graph-Based Protocols)

  19. 트리규약(tree-protocol ):그래프 규약의 일종,lock-X만 허용 트랜잭션의 첫번째 잠금은 어떤 자료 항목에도 걸릴 수 있음 그 후 계속해서 자료 Q는 Ti에의하여 잠길 수 있다. 단, Q의 부모 노드는 현재 Ti에 의하여 잠겨있다. 자료항목들은 언제라도 풀릴 수 있다. Ti에 의해 잠금이 걸렸다 풀린 자료 항목은 또 다시 Ti에 의하여 잠금이 걸릴 수 없다. Tree Protocol

  20. The tree protocol ensures conflict serializability as well as freedom from deadlock. 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. Graph-Based Protocols (Cont.)

  21. 각 트랜잭션은 시스템에 들어가면 시간도장(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. 타임스탬프 기반 규약(Timestamp-Based Protocols)

  22. 시간도장 순서규약에서 어떤 충돌 읽기,쓰기 연산은 시간도장순으로 실행됨을 보장함. 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). (선배가 쓴 것은 읽을 수 있음) Timestamp-Based Protocols (Cont.) W-timestamp Ti Q R-timestamp Tj

  23. 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). Timestamp-Based Protocols (Cont.)

  24. A partial schedule for several data items for transactions with timestamps 1, 2, 3, 4, 5 Example Use of the Protocol T1 T2 T3 T4 T5 read(X) read(Y) read(Y) write(Y) write(Z) read(Z) read(X) abort read(X) write(Z) abort write(Y) write(Z)

  25. (572쪽) 시간도장 순서규약은 직렬성을 보장한다. 그것은 연산들이시간도장 순서에 따라 처리되기 때문이다. 이 규약은 교착상태도 해결한다. 이유는 대기상태에 있는 트랜잭션이 없기 때문이다. 짧은 트랜잭션과 충돌로 긴 트랜잭션이 계속 재시작할 경우 기아상태가 발생할 수 있다. 복구가능한 스케줄을 생성할 수도 있다. Correctness of Timestamp-Ordering Protocol transaction with smaller timestamp transaction with larger timestamp

  26. Recoverability and Cascade Freedom • Problem with timestamp-ordering protocol: • Suppose Ti aborts, but Tj has read a data item written by Ti • Then Tjmust abort; if Tjhad 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

  27. 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. Thomas’Write Rule

  28. Execution of transaction Tiis 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 검증기반규약 (Validation-Based Protocol)

  29. 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. Validation-Based Protocol (Cont.)

  30. 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 Tjdo 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 Tjdoes not read any item written by Ti. Validation Test for Transaction Tj start(Ti) finish(Ti) start(Ti) finish(Ti) finish(Tj) start(Tj) start(Tj) validation(Tj)

  31. Example of schedule produced using validation Schedule Produced by Validation T14 T15 read(B) read(B) B:- B-50 read(A) A:- A+50 read(A) (validate) display (A+B) (validate) write (B) write (A)

  32. (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 Multiple Granularity

  33. The highest level in the example hierarchy is the entire database. The levels below are of type area, file and record in that order. Example of Granularity Hierarchy

  34. 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. Intention Lock Modes

  35. The compatibility matrix for all lock modes is: Compatibility Matrix with Intention Lock Modes S IX S IX X IS  IS      IX     S      S IX      X     

  36. 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, Tiis two-phase). 6. Tican 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. Multiple Granularity Locking Scheme

  37. 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. Multiversion Schemes

  38. 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 Ticreates 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). Multiversion Timestamp Ordering

  39. The multiversion timestamp scheme presented next ensures serializability. Suppose that transaction Tiissues 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. Multiversion Timestamp Ordering (Cont)

  40. 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. Multiversion Two-Phase Locking

  41. 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. Multiversion Two-Phase Locking (Cont.)

  42. Consider the following two transactions: T1: write (X) T2: write(Y) write(Y) write(X) Schedule with deadlock 교착상태처리(Deadlock Handling) T1 T2 lock-X on X write (X) lock-X on Y write (X) wait for lock-X on X wait for lock-X on Y

  43. 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 preventionprotocols 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). Deadlock Handling

  44. 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. More Deadlock Prevention Strategies

  45. 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. Deadlock prevention (Cont.)

  46. 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 Tjis 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 TiTj 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. Deadlock Detection

  47. Deadlock Detection (Cont.) Wait-for graph with a cycle Wait-for graph without a cycle

  48. 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 Deadlock Recovery

  49. 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. Insert and Delete Operations

  50. 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. Insert and Delete Operations (Cont.)

More Related