Junior — Middle
What methods can be used to prevent the use of pessimistic locking in Java applications?
sobes.tech AI
Answer from AI
Pessimistic locking involves acquiring locks on resources before performing operations, which can lead to reduced performance and deadlocks. To prevent its use in Java applications, the following approaches can be applied:
- Use optimistic locking, for example, with a version or timestamp in the database. When updating, check that the data has not changed since it was read.
- Apply non-blocking algorithms and data structures from the
java.util.concurrentpackage. - Minimize the scope and duration of locks by using finer-grained locks or lock-free approaches.
- Use transaction mechanisms with retries in case of conflicts.
- In ORM frameworks (e.g., Hibernate), configure the lock strategy to optimistic.
Example of optimistic locking with versioning in JPA:
@Entity
public class Product {
@Id
private Long id;
@Version
private int version;
private int quantity;
// getters and setters
}
When updating, JPA will check the version and throw an exception if the data has been modified by another transaction.