Reading without taking a lock
A stamped lock adds an optimistic read mode on top of normal read and write locks. An optimistic reader takes no lock at all. It grabs a version stamp, reads the data, then checks whether the stamp is still valid.
The optimistic flow
- Call try optimistic read to get a stamp reflecting the current version.
- Read the fields into local variables.
- Call validate with the stamp. If no writer intervened it returns true and the read is good.
- If validation fails, fall back to acquiring a real read lock and read again.
Because the happy path takes no lock and writes no shared memory, it scales beautifully when writes are rare. There is no cache line bouncing from incrementing a reader count.
The catch
Optimistic reads can observe torn or inconsistent state mid read, so you must copy fields locally and only trust them after validation. Never act on optimistically read values before validate succeeds.
Key idea
A stamped lock lets readers skip locking entirely on the common path by validating a version stamp, gaining scalability when writes are rare, at the cost of copying fields and rereading whenever a writer interferes.