Two philosophies of conflict
Pessimistic locking assumes conflicts are likely, so a thread takes a lock before touching data and holds it through the whole operation. Optimistic locking assumes conflicts are rare, so a thread proceeds without a lock and only checks at the end whether anyone interfered.
How optimistic works
The optimistic pattern reads data along with a version or timestamp, does its work on a local copy, then at commit time verifies the version is unchanged. If it matches, the write commits. If another thread bumped the version, the commit is rejected and the operation retries from the top.
The tradeoff
- Pessimistic pays the lock cost on every operation, including the common case with no conflict, and risks contention and deadlock. But it never wastes work, since it never aborts.
- Optimistic pays almost nothing when conflicts are rare, and avoids holding locks. But under high contention it wastes work on repeated retries and can livelock if everyone keeps colliding.
Choosing
Optimistic suits read heavy, low conflict workloads such as version stamped database rows. Pessimistic suits hot, write heavy data where retries would thrash.
Key idea
Pessimistic locks up front and never aborts, optimistic validates at commit and retries, so match the strategy to the conflict rate.