Explain working of two phase locking protocol.
In : BE Subject : Database Management SystemsThe main problem 2PL solves is preventing conflicts between concurrent transactions (e.g., lost updates, dirty reads, incorrect summaries) to ensure serializability—the concept that the final outcome of running transactions concurrently is equivalent to running them one after another in some order.
The Two-Phase Locking (2PL) protocol is a set of rules in a DBMS that manages how transactions lock data to prevent conflicts when multiple transactions happen at once. Its main goal is to ensure that the final outcome is correct and consistent, as if the transactions ran one after another.
The protocol is called "two-phase" because every transaction must go through two strict, consecutive phases. First, in the growing phase, the transaction is only allowed to acquire new locks on data it needs to read or write; it cannot release any locks during this time. Second, in the shrinking phase, the transaction can only release the locks it has already acquired; it is forbidden from asking for any new locks. This simple rule of separating locking and unlocking into two distinct phases guarantees that transactions won't interfere with each other in a way that leads to inconsistent data.
A common and stricter version used in practice is Strict 2PL. This variant adds one crucial rule: a transaction must hold onto all its exclusive (write) locks until it either commits or aborts. This prevents other transactions from reading uncommitted data that might later be rolled back, effectively eliminating the risk of "cascading rollbacks" and making the system more robust.