Course contentsShow
← Software Engineering
Lesson 915 of 1,93328. Transactions and ConsistencyFree lesson

Shared and Exclusive Locks

How read locks allow concurrent readers while write locks ensure exclusive access to data.

Shared and Exclusive Locks

What you'll learn: How databases use two types of locks — shared locks for reading and exclusive locks for writing — to balance concurrent access with data integrity.


The Library Book Analogy

Imagine a popular library book. Multiple people can read it simultaneously if they all just look at it (shared access). But if someone needs to write corrections in the book, they need exclusive access — no one else can read or write while changes are being made.

Databases work the same way with locks.

Shared Locks (Read Locks)

A shared lock is acquired when a transaction wants to read data. Multiple transactions can hold shared locks on the same data simultaneously because reading doesn't change anything. This allows concurrent readers to work in parallel without blocking each other.

When you read data under pessimistic locking, you're likely acquiring a shared lock.

Exclusive Locks (Write Locks)

An exclusive lock is required when a transaction wants to write (update, insert, or delete) data. Only one transaction can hold an exclusive lock on a piece of data at a time. While an exclusive lock is held:

  • No other transaction can acquire a shared lock (can't read)
  • No other transaction can acquire an exclusive lock (can't write)

This prevents conflicts where multiple transactions try to modify the same data simultaneously.

Lock Compatibility

  • Shared + Shared: ✅ Compatible (multiple readers)
  • Shared + Exclusive: ❌ Incompatible (reader must wait for writer)
  • Exclusive + Exclusive: ❌ Incompatible (writer must wait for writer)

This system ensures that reads don't block other reads, but writes get the exclusive access they need to maintain consistency.

Key Takeaway: Shared locks enable concurrent reads for performance, while exclusive locks ensure safe, conflict-free writes by granting sole access to modifying transactions.