← Java / Spring · Contents

JAVA-068 / Advanced

Balance updates without pessimistic or optimistic locking (race condition)

A04:2021 Insecure Design · CWE-362 Race Condition · CWE-367 TOCTOU

Why is this a problem?

Concurrent withdrawals can produce a negative balance.

How to fix it

java
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select a from Account a where a.id = :id")
Optional<Account> findForUpdate(@Param("id") Long id);
// Alternatively, optimistic locking with @Version and retry

Further reading