How to implement optimistic locking in code? What happens in case of a version conflict?
sobes.tech AI
Answer from AI
Optimistic locking is a concurrency control strategy where no explicit lock is placed when reading data, and conflict checking occurs during writing.
Implementation in Java typically relies on the version of the object (for example, a version field), which is incremented with each update. When saving, it checks whether the version of the object in the database matches the version the client was working with.
Example:
@Entity
public class Product {
@Id
private Long id;
private String name;
@Version
private Integer version; // field for optimistic locking
}
// In the service
public void updateProduct(Product updatedProduct) {
Product current = productRepository.findById(updatedProduct.getId()).orElseThrow();
if (!current.getVersion().equals(updatedProduct.getVersion())) {
throw new OptimisticLockingFailureException("Object version is outdated");
}
// update fields
current.setName(updatedProduct.getName());
productRepository.save(current);
}
In case of version conflict (when someone else has already updated the object and increased the version), an exception occurs, which can be handled, for example, by retrying the operation or notifying the user about the conflict. This prevents data loss and ensures integrity during concurrent modifications.