What is the difference between a lock and a latch in the context of concurrent access to a database?

From CMU 15-721 (Spring 2016), lecture 6 presentation, slides 25 and 26, which cites A Survey of B-Tree Locking Techniques by Goetz Graefe:

Locks
→ Protects the index’s logical contents from other txns.
→ Held for txn duration.
→ Need to be able to rollback changes.

Latches
→ Protects the critical sections of the index’s internal data structure from other threads.
→ Held for operation duration.
→ Do not need to be able to rollback changes.

Locks and latches


It really depends on your DBMS, but here's a good explanation for Oracle.

http://www.dba-oracle.com/t_lru_latches.htm

Latches are like locks for RAM memory structures to prevent concurrent access and ensure serial execution of kernel code. The LRU (least recently used) latches are used when seeking, adding, or removing a buffer from the buffer cache, an action that can only be done by one process at a time.


Another name for a latch is 'spin lock'. It's a simple 'while loop' until bit will be zero (depending on implementation). The execution thread is never asleep while the latch is not available. No any queue. A spin lock is useful for short-time memory object locking, but wasteful if held for a longer duration. See the "Spinlock" article on Wikipedia

Locks are usually supported by the system and in case that they are taken, your thread will be put to sleep so it won't consume any processor resources. Each lock keeps an internal queue of all suspended threads.

The lock manager is the subsystem that can provide you as spin locks as heavyweight locks for concurrency support.

See also the article by Tom Kyte about latches and locks.