Sobes.tech
Senior

What is pessimistic and optimistic locking?

sobes.tech AI

Answer from AI

Pessimistic and optimistic locking are two strategies for managing concurrent access to data.

Pessimistic locking assumes that conflicts will occur when accessing data, so a lock is set in advance to prevent simultaneous modification of the same data. For example, an exclusive or shared lock is placed when reading or writing an object, and other threads wait for the lock to be released. This reduces the likelihood of conflicts but can lead to deadlocks and decreased performance.

Optimistic locking assumes that conflicts are rare, so locks are not set in advance. Instead, when saving changes, it checks whether the data has been modified since it was read (for example, using a version or timestamp). If the data has changed, the operation is rolled back or retried. This increases concurrency but requires conflict handling.

In Java, optimistic locking is often implemented through version comparison (for example, in JPA with @Version), while pessimistic locking is implemented using synchronized, ReentrantLock, or database-level locks.