Skip to content

Locking

Locking are different strategies for handling concurrent access to data, i.e., when multiple transactions try to update the same data at the same time.

Optimistic Locking

Assumes conflicts are rare. It doesn't lock the data when reading, but checks before committing whether the data was modified by someone else.

How it works

A special field (usually a @Version field) is used.

When an entity is updated, JPA checks if the version has changed.

If it has, an exception (OptimisticLockException) is thrown.

java
@Version
private int version;

Use cases

  • High-read, low-write systems.
  • Where lock contention is unlikely.

Pessimistic Locking

Assumes conflicts are likely. It locks the data at the database level as soon as it’s read, so others can’t read or modify it until the lock is released.

How it works

A lock is explicitly requested (PESSIMISTIC_READ, PESSIMISTIC_WRITE) when querying.

The DB ensures no one else can interfere with the locked row.

java
User user = entityManager
    .find(User.class, userId, LockModeType.PESSIMISTIC_WRITE);

Use cases

  • High-conflict environments.
  • Anywhere data must not be changed concurrently.

Comparison

FeatureOptimistic LockingPessimistic Locking
Locking timeOnly to commit timeLocks immediately on access
PerformanceBetter (less locking)Slower (more locking)
Conflict handlingDetects at commitPrevents conflict upfront
Use caseLow contentionHigh contention
ExceptionOptimisticLockExceptionPessimisticLockException, timeouts

Contact: M_Bergmann AT gmx.at