π OptimisticLockException
Definition:
OptimisticLockException is an exception thrown in JPA/Hibernate when optimistic locking fails.
It happens when two or more transactions try to update the same entity simultaneously, and the version check fails.
1οΈβ£ Optimistic Locking Concept
- Optimistic locking does not lock rows in the database.
- Each row/entity has a version field (integer or timestamp).
-
When updating:
- Read the entity with its current version.
- Make changes.
- When saving, check if the version in DB matches the version read.
- If versions match, increment version and save.
- If versions donβt match, throw
OptimisticLockException.
2οΈβ£ Example
@Entity
public class Account {
@Id
private Long id;
private double balance;
@Version
private int version; // Optimistic lock version
}
Scenario:
- Transaction A reads account version = 1
- Transaction B reads account version = 1
- Transaction A updates balance β version increments to 2 β saved successfully
- Transaction B updates balance β version in DB = 2, but B read version = 1 β
OptimisticLockExceptionthrown
3οΈβ£ Why itβs useful
- Prevents lost updates in concurrent environments.
- Safer than pessimistic locking for high-concurrency systems.
- Works well when conflicts are rare, since no DB row locks are held.
4οΈβ£ How to handle it
- Retry transaction: Often, just retrying the operation works.
- Notify user: Let the user know their changes conflicted.
- Merge changes: Apply conflict resolution logic manually.
try {
accountRepository.save(account);
} catch (OptimisticLockException e) {
// retry or show error
}
5οΈβ£ Key Points
- Uses a version column (
@Version) in JPA/Hibernate. - Exception occurs at commit/update, not at read.
- Suitable for high-concurrency systems where conflicts are rare.
- Lightweight compared to pessimistic locking.
π‘ Analogy:
Think of it like signing a document:
- You read the latest version of the doc.
- Make your edits.
- When saving, the system checks if the doc has been edited since you read it.
- If yes β conflict β
OptimisticLockException.