Middle+
What are optimistic and pessimistic locking? How to implement them?
sobes.tech AI
Answer from AI
Optimistic locking assumes that conflicts during data access will not occur and does not lock the resource in advance. When saving changes, it checks whether the resource has been modified since it was read. If it has, the operation is rolled back or retried.
Pessimistic locking locks the resource immediately at the start of the operation so that no other process can modify it until the operation is complete.
Implementation:
- Optimistic locking is often implemented using a data version or timestamp. For example, a
versionfield is added to the database. When updating, it checks if the version matches; if not, it rolls back.
// example of optimistic locking with version
@Transactional
public void updateEntity(Entity e) {
Entity current = repository.findById(e.getId());
if (!current.getVersion().equals(e.getVersion())) {
throw new OptimisticLockException();
}
e.setVersion(e.getVersion() + 1);
repository.save(e);
}
- Pessimistic locking is implemented through database locks or in code (synchronized, Lock). For example, in Java:
Lock lock = new ReentrantLock();
lock.lock();
try {
// work with resource
} finally {
lock.unlock();
}
Or in SQL:
SELECT * FROM table WHERE id = ? FOR UPDATE;
The choice depends on the likelihood of conflicts and performance requirements.