Skip to the content.

πŸ”‘ 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


2️⃣ Example

@Entity
public class Account {
    @Id
    private Long id;

    private double balance;

    @Version
    private int version;  // Optimistic lock version
}

Scenario:

  1. Transaction A reads account version = 1
  2. Transaction B reads account version = 1
  3. Transaction A updates balance β†’ version increments to 2 β†’ saved successfully
  4. Transaction B updates balance β†’ version in DB = 2, but B read version = 1 β†’ OptimisticLockException thrown

3️⃣ Why it’s useful


4️⃣ How to handle it

  1. Retry transaction: Often, just retrying the operation works.
  2. Notify user: Let the user know their changes conflicted.
  3. Merge changes: Apply conflict resolution logic manually.
try {
    accountRepository.save(account);
} catch (OptimisticLockException e) {
    // retry or show error
}

5️⃣ Key Points


πŸ’‘ Analogy:

Think of it like signing a document: