Video in progress

Strong Junior 🐻 Hibernate and JPA

What is a pessimistic lock and how do you get one in JPA?

A pessimistic lock locks the database row at the moment of reading, so other transactions can't change it and wait for the commit. In JPA you get it with LockModeType.PESSIMISTIC_WRITE, which usually turns into SELECT ... FOR UPDATE.

📖 Answer

public interface AccountRepository extends JpaRepository<Account, Long> {

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("select a from Account a where a.id = :id")
    Optional<Account> findForUpdate(@Param("id") Long id);
}

@Transactional
public void withdraw(Long id, BigDecimal sum) {
    Account acc = repo.findForUpdate(id).orElseThrow(); // the row is locked
    acc.debit(sum);
}   // commit: the lock is released

If a second request tries to fetch the same account, it waits until the first one commits and then sees the updated balance.

How it differs from optimistic: @Version detects the conflict at the end and throws an error, while pessimistic prevents the conflict, at the price of waiting. Where conflicts are frequent (one popular account, stock in a warehouse), pessimistic is more convenient.

The risks:

  • a lock only makes sense inside a transaction; without @Transactional, Hibernate throws an error;
  • if two transactions lock two rows in opposite order, you get a deadlock. Always lock rows in the same order (by id, for example);
  • holding a lock inside a long transaction stalls everyone else. You can set a wait limit with the jakarta.persistence.lock.timeout hint.

There is also PESSIMISTIC_READ, which becomes FOR SHARE depending on the database.