Intermediate Topic 28 of 51 Databases
Locking and Two-Phase Locking
Using locks to serialize conflicting operations.
How it works
Databases lock data items to control access: shared locks allow concurrent reads and exclusive locks allow a single writer. Locks may cover rows, pages, tables or ranges, and intention locks mark higher-level interest. Two-phase locking splits a transaction into a growing phase, where it only acquires locks, and a shrinking phase, where it only releases them; this guarantees serializable schedules. Strict 2PL holds exclusive locks until commit to prevent cascading aborts.
Step-by-step walkthrough
- A transaction acquires locks as it works, shared for reads and exclusive for writes.
- In two-phase locking it may not take new locks after releasing one.
- It holds all locks until commit.
- Then all locks are released together.
- This guarantees serializability but can deadlock, so the manager detects cycles.
Where it is used
Relational databases, lock managers in distributed systems and SELECT FOR UPDATE row locking in applications use these protocols.
Common pitfall
Two-phase locking can deadlock, so the database detects cycles or uses timeouts and aborts a victim. Coarse locks reduce concurrency and fine ones increase overhead. Lock escalation can unexpectedly block many users. Long transactions hold locks and cause pile-ups. Acquire locks in a consistent order and keep transactions short.
Where it fits in the course
Locking and Two-Phase Locking is topic 28 of 51 in Databases, rated Intermediate. It follows Concurrency Control. The next topic is MVCC.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Databases quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Databases quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Locking and Two-Phase Locking?
Where do people use Locking and Two-Phase Locking?
What is the most common mistake with Locking and Two-Phase Locking?
What should I learn before this topic?
How can I practice it?
Is Locking and Two-Phase Locking hard to learn?
How long does it take to learn Locking and Two-Phase Locking?
Which topics are related to Locking and Two-Phase Locking?
What should I study after Locking and Two-Phase Locking?
Related topics
- Concurrency Control (Databases)
- MVCC (Databases)
- Isolation Levels (Databases)
- Stored Procedures and Triggers (Databases)
- Two-Phase Commit (Distributed Systems & Cloud)