MySQL Locks
Global Lock
Generally used when doing full database backup. It blocks write operations and only allows read requests. Therefore, it’s usually chosen during business low-peak periods for full database backup.
| |
Table-Level Locks
Table Lock
- Table shared read lock. Multiple threads can acquire this lock simultaneously. Threads with this lock can read the table but cannot write to it. MyISAM acquires table shared read locks when processing read requests. InnoDB defaults to row locks and handles read requests through MVCC.
- Table exclusive write lock. Only one thread can acquire this lock and perform write operations on the table. No other threads can read this table.
| |
Table locks are triggered by: ALTER/DROP/TRUNCATE TABLE
Intention Locks
Intention locks are table-level locks, and their main purpose is to avoid full table scans. (🌟 operations demonstrate this) In InnoDB, reading a record uses the lock-free MVCC mechanism, which doesn’t add intention locks to the table.
Intention locks don’t conflict with row-level locks, and intention locks don’t conflict with each other.
| Lock Type | Table S Lock (Shared) | Table X Lock (Exclusive) | Table IS Lock (Intention Shared) | Table IX Lock (Intention Exclusive) |
|---|---|---|---|---|
| Table S Lock (Shared) | Compatible | Conflict | Compatible | Compatible |
| Table X Lock (Exclusive) | Conflict | Conflict | Conflict | Conflict |
| Table IS Lock (Intention Shared) | Compatible | Conflict | Compatible | Compatible |
| Table IX Lock (Intention Exclusive) | Conflict | Conflict | Compatible | Compatible |
Intention Shared Lock (IS)
| |
When we read a row using this operation, it adds a row-level read lock to that row, and the database also adds a table-level intention shared lock to the table.
- When another thread tries to add a write lock to a specific row, it checks the index to see if the row has a read lock. If not, the write lock can be acquired; if the row already has a read lock, the write lock cannot be added.
- When another thread tries to add a write lock to the entire table, it discovers the table already has an intention shared lock, so the write operation cannot be completed. 🌟
- When another thread tries to add a read lock to a specific row/entire table, there’s no conflict.
Intention Exclusive Lock (IX)
| |
This operation adds an intention exclusive lock to the table and adds a write lock to the specific row.