What is the difference between optimistic locking and pessimistic locking?

Asked 29 days ago Updated 8 days ago 90 views

1 Answer


0

Optimistic Locking assumes conflicts are rare. Multiple users can read and update the same data concurrently. Before saving, the system checks whether the data has been modified by someone else (usually using a version number or timestamp). If a conflict is detected, the update is rejected and must be retried.

Pessimistic Locking assumes conflicts are likely. When a user accesses data for modification, the system locks it immediately, preventing others from modifying it until the lock is released.

Example

  • Optimistic Locking: Two users edit the same record. The first saves successfully; the second gets a version conflict error.
  • Pessimistic Locking: The first user locks the record while editing, so the second user must wait until the lock is released.

Key Difference

  • Optimistic Locking: Better performance and concurrency, but may require retries.
  • Pessimistic Locking: Prevents conflicts upfront, but can reduce concurrency and cause blocking.

One-line interview answer:
"Optimistic locking detects conflicts at commit time using version checks, while pessimistic locking prevents conflicts by locking the resource before updates occur."

Write Your Answer