Locking
Locking are different strategies for handling concurrent access to data, i.e., when multiple transactions try to update the same data at the same time.
Optimistic Locking
Assumes conflicts are rare. It doesn't lock the data when reading, but checks before committing whether the data was modified by someone else.
How it works
A special field (usually a @Version
field) is used.
When an entity is updated, JPA checks if the version has changed.
If it has, an exception (OptimisticLockException
) is thrown.
@Version
private int version;
Use cases
- High-read, low-write systems.
- Where lock contention is unlikely.
Pessimistic Locking
Assumes conflicts are likely. It locks the data at the database level as soon as it’s read, so others can’t read or modify it until the lock is released.
How it works
A lock is explicitly requested (PESSIMISTIC_READ
, PESSIMISTIC_WRITE
) when querying.
The DB ensures no one else can interfere with the locked row.
User user = entityManager
.find(User.class, userId, LockModeType.PESSIMISTIC_WRITE);
Use cases
- High-conflict environments.
- Anywhere data must not be changed concurrently.
Comparison
Feature | Optimistic Locking | Pessimistic Locking |
---|---|---|
Locking time | Only to commit time | Locks immediately on access |
Performance | Better (less locking) | Slower (more locking) |
Conflict handling | Detects at commit | Prevents conflict upfront |
Use case | Low contention | High contention |
Exception | OptimisticLockException | PessimisticLockException , timeouts |