Sobes.tech
Middle+

What is the difference between optimistic and pessimistic locking in Hibernate?

sobes.tech AI

Answer from AI

Optimistic locking assumes that data modification conflicts are rare and checks for conflicts only when saving. Pessimistic locking assumes that conflicts can occur frequently and locks data at the database level immediately after retrieval.

Main differences:

Characteristic Optimistic Locking Pessimistic Locking
When does locking occur When attempting to save a modified object. Uses a versioning mechanism (version field or timestamp). When loading an object from the database. Uses database-level locking (SELECT ... FOR UPDATE).
Conflict probability Low. High.
Performance Higher in case of rare conflicts, as there are no overheads for database locking. Lower in case of frequent conflicts or long transactions due to resource locking in the database.
Application When transactions are short and the probability of concurrent modifications of the same data is low. When the probability of concurrent modifications of the same resources is high and guaranteed exclusive access is required.
Type of lock Logical (at the application level, via versioning). Physical (at the database level).

Example of optimistic locking using a version field:

// entities.User.java
@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @Version // Hibernate adds version check during update
    private int version;

    // ... getters and setters
}

Example of pessimistic locking during load:

// dao.UserRepository.java
public User findByIdWithPessimisticWriteLock(Long id) {
    return entityManager.find(User.class, id, LockModeType.PESSIMISTIC_WRITE);
}