Skip to content
We areTOP 1%

What are shared and exclusive locks?

EasyConceptConcurrency Control & Locking
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

Answer

A lock is a marker that a transaction places on a data item to control how other transactions may access it.

  • Shared (S) lock: taken for reading. Many transactions can hold S locks on the same item at the same time.
  • Exclusive (X) lock: taken for writing. Only one transaction can hold it, and no other transaction can hold any lock on that item meanwhile.
  • A request that is not compatible with the locks already held must wait until they are released.
  • Locks have a granularity: row, page or table. Row locks allow more concurrency, while table locks have less overhead.

Example: The lock compatibility matrix:

             S held   X held
request S    yes      no
request X    no       no

In MySQL 8 and PostgreSQL, SELECT ... FOR SHARE takes a shared row lock and SELECT ... FOR UPDATE takes an exclusive one:

SELECT * FROM seats WHERE id = 7 FOR UPDATE;  -- others must wait to change seat 7

More in Concurrency Control & Locking

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account