What is the difference between optimistic and pessimistic locking?
sobes.tech AI
Answer from AI
Optimistic and pessimistic locking are two approaches to managing concurrent access to data.
-
Pessimistic locking assumes conflicts will occur, so when accessing a resource, it is immediately locked, and other operations wait for it to be released. It is used in systems with high contention and frequent conflicts.
-
Optimistic locking assumes conflicts are rare. Data is not locked during reading, but when writing, it checks whether the data has changed since it was read (for example, by version or timestamp). If there are changes, the operation is rolled back or retried.
Example: in a database with optimistic locking, you can store a record version and check if the version matches during an update to avoid overwriting others' changes.