Two Phase Locking (2PL) Protocol
- 2-PL is an extension of Shared/Exclusive locking.
- It is used to reduce the problems of Shared/Exclusive locking
- Any schedule that follows 2PL will always be serializable, which was not in Shared/Exclusive locking
Phases of 2PL
There are two basic phases of two-phase locking, which are explained below
I. Growing Phase: In the Growing phase, only Locks are acquired by a transaction and no locks are released by a transaction at that time.
II. Shrinking Phase: In the shrinking phase, only Locks are released by transaction, and no locks are acquired by a transaction at that time.
Important in 2PL is Lock Point
Lock Point: The Point at which the growing phase ends (i.e., when the transaction takes the final lock) is called Lock Point.
Example: The following diagrams show growing and shrinking phases in 2-PL.
- Growing Phase: From Time 1 to 3.
- Shrinking Phase: From Time 5 to 7
- Lock Point: At time 3
- Growing Phase: From Time 2 to 6
- Shrinking Phase: From Time 8 to 9
- Lock Point: At Time 6
2PL Transaction Execution Sequence
As we say, 2PL will generate the serial schedule, then what will be the sequence of transaction execution?
Answer: If the locking point of Transaction T1 comes earlier than Transaction T2, then the T1 will execute first than T2. As given below in the diagram
Important: Keep in mind when multiple transactions need to acquire the shared or exclusive lock, then it must follow the lock compatibility table.
In the following schedule, T1 holds the shared lock on “A,” and T2 also requires an exclusive lock on “A”. This case is not possible according to the lock compatibility table. So, T2 will be blocked(waiting state) until T1 releases the exclusive lock on “A”.
Advantages of 2-PL
2PL always ensures the Serializability. It means the schedule in 2PL must be serial. No loop exists in the transaction execution sequence graph.
Disadvantages of 2-PL
1. Produced schedule through 2PL locking may be irrecoverable
2. Produced schedule through 2PL locking may contain a deadlock problem
3. Produced schedule through 2PL locking may contain a Starvation Problem
4. Cascading Rollback Problem
If the rollback of one transaction causes the rollback of other dependent transactions, it is called cascading rollback.
As 2PL removes the irrecoverability problem, cascading, deadlock, and starvation problems are still there. To remove such problems, we use different types of 2PL.
We will see types of 2PL in the next lecture.