Video in progress
When do you need a pessimistic lock (@Lock(PESSIMISTIC_WRITE)), and what are its risks?
It locks the row at read time (SELECT ... FOR UPDATE), and others queue up to modify it. You need it when conflicts are frequent and a retry is expensive. The risks are waiting, deadlocks and pool exhaustion.
📖 Answer
public interface WalletRepository extends JpaRepository<Wallet, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
@QueryHints(@QueryHint(name = "jakarta.persistence.lock.timeout", value = "3000"))
@Query("select w from Wallet w where w.id = :id")
Optional<Wallet> lockById(@Param("id") long id);
}
@Transactional
public void withdraw(long walletId, BigDecimal amount) {
Wallet w = wallets.lockById(walletId).orElseThrow();
w.debit(amount); // others wait until the transaction ends
}
What to watch for:
- keep the transaction short. Don't make an external HTTP call while holding the lock: a payment API that takes 5 seconds to respond blocks the row for 5 seconds;
- set a timeout, otherwise the transaction can wait forever;
- deadlock: A→B and B→A between two wallets at the same time is the classic case. Always acquire locks in the same order (for example, the smaller id first);
- without a transaction,
FOR UPDATEis released immediately or throws an error.
Often there is a simpler way, an atomic UPDATE:
update wallet set balance = balance - :amt where id = :id and balance >= :amt
If it returns 0 rows, there isn't enough money.
Sign up to mark studied questions and save your progress.