Junior — Middle
Explain the principle of optimistic locking and how it differs from pessimistic locking.
sobes.tech AI
Answer from AI
Optimistic locking assumes that conflicts during concurrent data access are rare. Operations are performed without locks, and before saving changes, it is checked whether the data has changed since it was read. If the data has changed, the operation is rolled back or retried.
Pessimistic locking, on the other hand, assumes that conflicts are likely, so data is locked during the operation to prevent other processes from modifying it.
Example:
- Optimistic locking: when updating a database record, the version of the record is checked. If the version has changed since it was read, the update is canceled.
- Pessimistic locking: when reading a record, a lock is placed, and other operations wait until it is released.
Optimistic locking is better suited for systems with low contention, while pessimistic locking is more appropriate for high-concurrency environments.