Scrivio Interview library
CodingFoundations5 min read · updated 12 November 2026

Write a Spring Data JPA method that loads an account with SELECT ... FOR UPDATE and explain when you would use it.

We add @Lock(LockModeType.PESSIMISTIC_WRITE) to a repository query, @Query("select a from Account a where a.id = :id") Optional<Account> findForUpdate(@Param("id") Long id), and Hibernate appends FOR UPDATE to the SQL. It must run inside a transaction, because the row lock lasts until commit or rollback. I use it when conflicts on the same row are frequent and retries would be costly, such as balance updates on a hot account, with a lock timeout set through the jakarta.persistence.lock.timeout hint; PESSIMISTIC_READ maps to a shared lock such as FOR SHARE.

Why this question is asked

Optimistic locking works well when conflicts are rare, but when many requests update the same row, most of them fail and retry, and the retries themselves collide. Pessimistic locking makes them wait in line instead. Interviewers ask for this code to see whether we know the exact annotations, the transaction requirement, and when the trade-off is worth it. In this answer, we will write the method, see the SQL, use it in a service, add a timeout, compare it with the read lock, and decide when to use it.

1A Quick Recap of Row Locks

SELECT ... FOR UPDATE reads a row and locks it for writing. Until our transaction ends, any other transaction that tries to update that row, delete it, or lock it with FOR UPDATE has to wait. Plain reads are not blocked in PostgreSQL or MySQL InnoDB, because they read a consistent snapshot. When we commit or roll back, the lock is released and the next waiting transaction continues, now seeing our committed change.

2Writing the Repository Method

In Spring Data JPA, @Lock on a query method sets the JPA lock mode for that query. PESSIMISTIC_WRITE asks for an exclusive row lock.

Java
public interface AccountRepository extends JpaRepository<Account, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
@QueryHints(@QueryHint(name = "jakarta.persistence.lock.timeout", value = "3000"))
@Query("select a from Account a where a.id = :id")
Optional<Account> findForUpdate(@Param("id") Long id);
}
// PostgreSQL SQL generated by Hibernate:
// select a.id, a.balance, a.version from account a where a.id = ? for update

The @Query is optional for a simple lookup; @Lock also works on a derived method such as findById declared in the interface. Writing the query keeps the intent obvious, and the name findForUpdate tells every caller that this method locks.

3Using It Inside a Transaction

The lock lasts until the transaction ends, so the method only makes sense inside one. If we call it without a transaction, Hibernate refuses to run a locking query outside a transaction and throws, which is a helpful failure rather than a silent one; check your version for the exact exception.

Java
@Service
class TransferService {
@Transactional
public void withdraw(long accountId, BigDecimal amount) {
Account a = accounts.findForUpdate(accountId).orElseThrow(); // waits if another tx holds the lock
if (a.getBalance().compareTo(amount) < 0) {
throw new InsufficientFunds(accountId);
}
a.setBalance(a.getBalance().subtract(amount));
} // commit releases the lock
}
// balance 100; two concurrent withdrawals of 70:
// tx 1: lock, 100 >= 70, balance 30, commit
// tx 2: waits, then reads 30, 30 < 70 -> InsufficientFunds
Step throughTwo withdrawals on one account
Tx 1Account rowTx 2
select ... for update: lock granted
select ... for update: waits
update balance 30, commit
lock granted, reads balance 30
30 < 70: InsufficientFunds, roll back

5 messages in order. Play them, or step through them one at a time.

The second transaction reads the committed result of the first.

Notice that the check and the update happen while we hold the lock, so the second transaction cannot read the old balance. It waits, then sees 30 and correctly refuses. The transaction should be short: no remote calls while holding the lock, because every waiting request waits for those too.

4Setting a Lock Timeout

Without a timeout, a request can wait as long as the lock holder takes, which during an incident means until the HTTP client gives up. The JPA hint jakarta.persistence.lock.timeout sets the maximum wait in milliseconds; when it expires, Spring reports a PessimisticLockingFailureException subclass such as CannotAcquireLockException, which we can turn into a 409 or a retry.

How the hint becomes SQL depends on the database. On Oracle it becomes FOR UPDATE WAIT 3, and a value of 0 becomes NOWAIT on databases that support it. PostgreSQL has no per-statement wait clause, so support for positive timeouts there depends on the Hibernate version and dialect; check your version, and if needed set the PostgreSQL lock_timeout parameter, for example with SET LOCAL lock_timeout = '3s' at the start of the transaction or on the service's database role.

5PESSIMISTIC_READ and When to Use Which

PESSIMISTIC_READ asks for a shared lock, which allows other readers to take the same shared lock but blocks writers. On PostgreSQL and MySQL 8 it becomes FOR SHARE. It fits a case where we must make sure a row does not change while we use it, such as reading a currency rate that other rows depend on, without blocking other readers that do the same.

I choose PESSIMISTIC_WRITE when the same row is updated often and a failed attempt is expensive to repeat: a hot account receiving many payments, a shared counter, a single inventory row during a sale. With optimistic locking, ten concurrent requests on one row produce nine failures, and their retries collide again. With a row lock they simply queue. For rows that are rarely edited concurrently, like a customer profile, optimistic locking is better because it holds no locks at all. And when the whole operation fits in one statement, an atomic update such as update account set balance = balance - ? where id = ? and balance >= ? is better than both.

6Follow-up questions

Can pessimistic locks cause deadlocks?

Yes. If one transaction locks account A then B, and another locks B then A, each waits for the other. The database detects it and aborts one with a deadlock error. The standard fix is to always lock rows in the same order, for example by ascending id.

Does FOR UPDATE lock rows that do not exist yet?

No. It locks only rows the query returns, so it cannot stop another transaction from inserting a new matching row. A unique constraint, or a lock on a parent row that every insert must also lock, is needed for that.

Should the entity still have @Version when we use pessimistic locks?

It is a good idea. Code paths that do not use findForUpdate, such as an admin screen or a batch job, are still protected against lost updates by the version check.

7Conclusion

In this answer, we wrote a Spring Data JPA method with @Lock(LockModeType.PESSIMISTIC_WRITE) that Hibernate turns into SELECT ... FOR UPDATE, and saw that it only works inside a transaction, because the lock is held until commit or rollback. We added a lock timeout with the jakarta.persistence.lock.timeout hint, noted how it maps to each database, compared PESSIMISTIC_READ and FOR SHARE, and chose pessimistic locking for hot rows where retries would be costly.

What to say in the interviewAbout 80 seconds aloud

Open with

I would declare it in the repository: @Lock(LockModeType.PESSIMISTIC_WRITE) on a method with @Query select a from Account a where a.id = :id, returning Optional<Account>, called findForUpdate so callers know it locks.

Then, if they want more

Hibernate appends FOR UPDATE, so the database gives my transaction an exclusive lock on that row. That only works inside a transaction, because the lock is held until commit or rollback, so I call it from a @Transactional service method and do the check and the update while I hold the lock, with no remote calls in between.

A second withdrawal on the same account then waits and reads the committed balance, instead of reading the old one and causing a lost update.

I would add a lock timeout with the jakarta.persistence.lock.timeout hint, say 3000 milliseconds, and map the resulting lock failure to a 409 or a retry; on PostgreSQL I would check how my Hibernate version applies it and fall back to lock_timeout if needed. PESSIMISTIC_READ gives a shared lock, FOR SHARE, which blocks writers but not other readers.

I use pessimistic locking when one row gets many concurrent updates and retries would collide again, like a hot account, and optimistic locking when conflicts are rare.

About this answer

Last updated
12 November 2026
Versions it names
MySQL 8
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a Spring Data JPA method that loads an account with SELECT ... FOR UPDATE and...": https://scrivio-interview-library.netlify.app/databases/locking-and-concurrency-control/7ec502ee49/