Java.Hibernate.Middle.What is optimistic vs. pessimistic locking, and how do you implement them?

Short Answer

  • Optimistic locking assumes conflicts are rare → it lets multiple transactions read data simultaneously and checks for conflicts only at commit time (using a @Version field).
  • Pessimistic locking assumes conflicts are likely → it locks the data immediately so other transactions must wait or fail.

🔎 Optimistic Locking

✅ Use when data conflicts are rare and you want high concurrency.
✅ Implemented in Hibernate/JPA with the @Version annotation:

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

    private String name;

    @Version
    private int version; // Hibernate increments this field on each update
}

🔹 How it works:

  • Each update checks the current version value in the database.
  • If the version in the DB doesn’t match your entity’s version → someone else updated the record → Hibernate throws an OptimisticLockException.

🔹 Benefits:
✅ No DB locks → better performance under low contention.
❌ Fails at commit time if conflict → requires retry logic.

🔎 Pessimistic Locking

✅ Use when data conflicts are likely, or when you must prevent others from modifying or even reading until you finish.
✅ Hibernate supports it with explicit lock modes.

🔹 How to implement:

// Acquire a pessimistic write lock
Product product = em.find(Product.class, 1L, LockModeType.PESSIMISTIC_WRITE);

🔹 Lock modes:

  • PESSIMISTIC_READ → blocks writes but allows other reads.
  • PESSIMISTIC_WRITE → blocks both reads and writes.
  • PESSIMISTIC_FORCE_INCREMENT → like optimistic version increment, but forces update of the version.

🔹 JPQL with pessimistic lock:

Product product = em.createQuery(
    "SELECT p FROM Product p WHERE p.id = :id", Product.class)
    .setParameter("id", 1L)
    .setLockMode(LockModeType.PESSIMISTIC_WRITE)
    .getSingleResult();

🔹 Benefits:
✅ Immediate protection against concurrent updates.
❌ Can cause deadlocks or reduced concurrency if overused.

🔹 Important note on transactions:
Pessimistic locks hold database-level locks until the transaction commits or rolls back → always use them in a transaction context!

📊 Optimistic vs. Pessimistic Comparison

FeatureOptimistic LockingPessimistic Locking
When to useRare conflictsFrequent conflicts
Locking mechanismNo DB locks → uses @VersionDB-level locks
PerformanceHigher concurrencyLower concurrency
Failure timingAt commit timeAt data access time
RiskRetry needed on conflictDeadlocks, longer waits

📌 Key Takeaways

✅ Use optimistic locking with @Version for most use cases → best for web apps with short transactions.
✅ Use pessimistic locking when you must guarantee exclusive access → but carefully, as it can harm scalability.

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.