Two Phase Locking: Definition, Example, and Usage in DBMS
2PL) is a concurrency control method in databases that ensures transactions are executed safely without conflicts. It works by dividing the transaction process into two phases: a growing phase where locks are acquired, and a shrinking phase where locks are released, preventing conflicts and ensuring consistency.How It Works
Imagine you are organizing a group project where everyone needs to use shared resources like books or computers. To avoid confusion, you first collect all the resources you need before starting your work, and only after finishing, you return them. This is similar to how Two Phase Locking (2PL) works in databases.
In the first phase, called the growing phase, a transaction requests and obtains all the locks it needs on data items. No locks are released during this phase. Once it has all the locks, the transaction enters the shrinking phase, where it releases the locks but cannot acquire any new ones. This strict order prevents conflicts like two transactions changing the same data at the same time, ensuring data consistency.
Example
class TwoPhaseLocking: def __init__(self): self.locks = set() self.phase = 'growing' def acquire_lock(self, item): if self.phase == 'shrinking': raise Exception('Cannot acquire new locks in shrinking phase') print(f'Lock acquired on {item}') self.locks.add(item) def release_lock(self, item): print(f'Lock released on {item}') self.locks.discard(item) if not self.locks: self.phase = 'shrinking' # Simulate a transaction transaction = TwoPhaseLocking() transaction.acquire_lock('A') transaction.acquire_lock('B') transaction.release_lock('A') transaction.release_lock('B')
When to Use
Two Phase Locking is used in database systems to manage multiple transactions happening at the same time without causing errors or data corruption. It is especially useful when many users or applications access and modify the database concurrently.
For example, in banking systems where multiple transactions update account balances, 2PL ensures that each transaction completes fully without interference, preventing issues like lost updates or inconsistent data.
Key Points
- 2PL divides transaction locking into growing and shrinking phases.
- Locks are only acquired in the growing phase and only released in the shrinking phase.
- This method guarantees serializability, meaning transactions appear to run one after another.
- It prevents conflicts and ensures data consistency in concurrent transactions.