0% completed
Lock-based concurrency control is a mechanism where the database restricts access to data by allowing transactions to acquire locks on the data they access. Locks ensure that no two transactions can read or modify the same piece of data simultaneously, preventing conflicts and maintaining isolation.
Locks are used to:
Locks can be classified based on their purpose and scope:
It allows multiple transactions to read the same data simultaneously but prevents any transaction from modifying it.
It allows a transaction to modify data while preventing other transactions from reading or writing to the same data.
It is used to indicate a transaction’s intent to acquire a shared or exclusive lock on a specific part of the data.
Locks can be applied at different levels of granularity to balance performance and concurrency:
In this section, we explore the most common locking protocols used in database systems to enforce concurrency control, ensure isolation, and prevent conflicts during transaction execution. These include Two-Phase Locking, Predicate Locking, and Index-Range Locking.
Two-Phase Locking (2PL) is a concurrency control protocol that ensures serializability by dividing the locking process into two distinct phases: Expanding Phase and Shrinking Phase.
The table explains the compatibility of lock types in Two-Phase Locking. A Shared Lock allows multiple transactions to read the same data simultaneously, but no writes are allowed. An Exclusive Lock prevents any other transaction from reading or writing the data, ensuring isolation for write operations.
Lock Type | Shared Lock | Exclusive Lock |
---|---|---|
Shared Lock | Allowed | Not allowed |
Exclusive Lock | Not allowed | Not allowed |
Predicate locking extends 2PL by locking all objects that match a specified condition or predicate, including objects that do not currently exist but could potentially match the condition.
Record | Existence | Lock Acquired |
---|---|---|
1 | Yes | Yes |
2 | No | Yes |
3 | Yes | Yes |
Explanation
UPDATE table SET name = 'XYZ' WHERE id > 1
locks records 1, 2, and 3.Index-Range Locking is a simplified extension of predicate locking. It locks only the existing keys that match the predicate condition, leaving gaps between keys unlocked.
Record | Existence | Lock Acquired |
---|---|---|
1 | Yes | Yes |
2 | No | No |
3 | Yes | Yes |
Explanation
UPDATE table SET name = 'XYZ' WHERE id > 1
locks records 1 and 3.Aspect | Two-Phase Locking | Predicate Locking | Index-Range Locking |
---|---|---|---|
Lock Scope | Specific data items | All matching predicate rows | Existing matching keys only |
Concurrency | Medium | Low | High |
Overhead | Moderate | High | Low |
Use Case | Strong consistency | Complex queries, write skew | Indexed data with gaps |
.....
.....
.....