NOTE

Database Optimistic Locking and Pessimistic Locking

Optimistic locking checks conflicts when committing an update, while pessimistic locking locks data in advance. These notes compare both approaches and version-based implementations.

DatabasesCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Pessimistic Locking

select aaa from bbb where aaa=ccc for update

2. Optimistic Locking

Optimistic locking assumes that data conflicts generally will not occur, so it checks for conflicts only when an update is submitted.

  • Version number
    • Add a version field. Read the data first, then incorporate update xxx set version=version+1 where version=version into the original update statement; if the update fails, loop and retry.

3. Reference

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub