Sobes.tech
Senior

What are optimistic and pessimistic locking? When should each be used?

sobes.tech AI

Answer from AI

Optimistic and pessimistic locking are two approaches to managing concurrent access to data.

Optimistic locking assumes that conflicts during concurrent data modifications are rare. When reading data, no lock is placed, but upon saving, it checks whether the data has changed since it was read (for example, by version or timestamp). If the data has changed, the operation is rolled back or retried.

Pessimistic locking assumes that conflicts are likely, so data is locked during operations to prevent other transactions from modifying it.

When to use:

  • Optimistic locking is suitable for systems with low contention, where it's important not to lock resources and to ensure high performance.
  • Pessimistic locking is needed when the likelihood of conflicts is high, and it's crucial to avoid data loss or complex conflicts, such as in banking systems.

Example in Java with optimistic locking via version:

@Entity
public class Product {
    @Version
    private Long version;
    // other fields
}

When updating, Hibernate checks the version and throws an exception if the data has changed.

What are optimistic and pessimistic locking? When… - sobes.tech