Junior — Middle
How is optimistic locking implemented and what are its features?
sobes.tech AI
Answer from AI
Optimistic locking is an approach to managing concurrent access to data, where conflicts during simultaneous data modifications are assumed to be rare. Instead of locking the resource during operation, the system allows multiple transactions to work in parallel, and conflict checks are performed when saving changes.
Features of optimistic locking:
- Uses a version or checksum (e.g., a version field in the database).
- When updating, it checks that the data version has not changed since it was read.
- If the version has changed, the operation is rolled back or retried.
- Increases performance in systems with low contention.
Example in Java using JPA:
@Entity
public class Product {
@Id
private Long id;
private String name;
@Version
private int version; // field for optimistic locking
// getters and setters
}
// When updating:
// If someone else has changed the record and increased the version, an OptimisticLockException will be thrown upon saving.