Java.Hibernate.Beginner.What is pessimistic locking in Hibernate?

Pessimistic locking is a concurrency control strategy in Hibernate (and relational databases in general) where a row-level lock is acquired in the database as soon as you read or access a record, preventing other transactions from modifying it until your transaction completes.

🔹 Why use pessimistic locking?
✅ Ensures strong consistency when you need to prevent concurrent updates to the same record (e.g., financial transactions, inventory updates).
✅ Guarantees no other transaction can change or overwrite data you’re working with.

🔹 How does it work?

  • Hibernate issues SQL statements with lock hints like SELECT ... FOR UPDATE.
  • The database locks the rows until your transaction commits or rolls back.
  • Other transactions trying to acquire incompatible locks will block or fail with a timeout.

🔹 Example of using pessimistic lock in Hibernate:

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

User user = session.get(User.class, 1L, LockMode.PESSIMISTIC_WRITE); // lock user row

user.setUsername("newName");

tx.commit(); // releases the lock
session.close();

✅ Here, LockMode.PESSIMISTIC_WRITE instructs Hibernate to lock the selected row for exclusive writing → no other transaction can modify it simultaneously.

🔹 Lock modes for pessimistic locking:

  • LockMode.PESSIMISTIC_READ → acquire a shared lock to prevent other transactions from writing, but allow concurrent reads.
  • LockMode.PESSIMISTIC_WRITE → acquire an exclusive lock to prevent other reads or writes.
  • LockMode.PESSIMISTIC_FORCE_INCREMENT → lock and force a version increment for versioned entities.

🔹 SQL generated by Hibernate:
When using LockMode.PESSIMISTIC_WRITE, Hibernate typically issues:

SELECT * FROM users WHERE id = ? FOR UPDATE;

🔹 Key differences from optimistic locking:
Pessimistic locking → prevents concurrent updates up front by locking data immediately.
Optimistic locking → allows concurrent reads/updates but checks for conflicts when committing (e.g., using a @Version column).

🔹 When should you use pessimistic locking?
✅ When concurrent modifications must be strictly serialized.
✅ When data integrity is critical, and you can’t tolerate lost updates or write conflicts.
❌ Avoid pessimistic locks for high-throughput scenarios, as they can reduce concurrency and cause blocking.

Key takeaway:
Pessimistic locking in Hibernate acquires database locks immediately to prevent concurrent modifications, ensuring strong consistency — but should be used judiciously to avoid hurting performance.

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

Leave a Reply

Your email address will not be published.