Senior
What are optimistic and pessimistic locks in JPA/Hibernate? How are they implemented under the hood? When should each be used?
sobes.tech AI
Answer from AI
Optimistic locking and pessimistic locking are two approaches to managing concurrent access to data in JPA/Hibernate.
Optimistic Locking
- Based on the assumption that conflicts are rare.
- No locks are placed when reading data.
- When saving, the entity's version (usually the
@Versionfield) is checked. If the version has changed since reading, anOptimisticLockExceptionis thrown. - Allows avoiding database-level locks, increasing performance.
Under the hood: Hibernate adds a version field to the entity, and upon updating, checks that the version in the database matches the in-memory version, then increments it.
When to use:
- When the likelihood of conflicts is low.
- In high-load systems with many reads.
Pessimistic Locking
- Assumes conflicts are likely.
- When reading data, a lock is placed at the database level (e.g.,
SELECT ... FOR UPDATE). - Other transactions cannot modify or read the locked data until the lock is released.
Under the hood: Hibernate uses SQL queries with locks that are held until the end of the transaction.
When to use:
- When data changes frequently and conflicts are probable.
- In critical sections where avoiding conflicts is important.
Summary
- Optimistic locking is lightweight and better for systems with rare conflicts.
- Pessimistic locking is more strict and suitable for highly concurrent scenarios.
The choice depends on the application's nature and data integrity requirements.