Junior — Middle
Explain the principle of optimistic locking in data management systems.
sobes.tech AI
Answer from AI
Optimistic locking is an approach to managing concurrent access to data, where conflicts are assumed to be rare, and locks are not established in advance. Instead, when updating data, it is checked whether the data has changed since the last read.
Working principle:
- The client reads data along with a version or checksum.
- It makes necessary changes locally.
- When attempting to write, it checks whether the current data version matches the one read earlier.
- If the versions match, the update is successful.
- If the versions do not match, it means the data has been modified by another process, and the operation is rolled back or retried.
In Java, this is often implemented through a version field in the entity and the @Version annotation when using JPA/Hibernate.
Example:
@Entity
public class Product {
@Id
private Long id;
private String name;
@Version
private int version; // field for optimistic locking
// getters and setters
}