How to Use Pessimistic Locking in JPA and Spring Data
Use PESSIMISTIC_WRITE and SKIP LOCKED in JPA and Spring Data, set lock timeouts, handle lock exceptions and know when optimistic locking is the better choice.

Two requests try to take the last unit of stock at the same moment. Without coordination, both read stock = 1, both decide the sale is fine and the inventory ends at minus one. JPA gives you two answers: version the row and detect the conflict after the fact, which is optimistic locking, or lock the row up front so the second request waits, which is pessimistic locking. This post covers the second one: how to request the lock, how to configure timeouts and skipping, how to handle failures and when to choose it. The optimistic alternative is in optimistic locking with a version column.
What pessimistic locking does
When you read a row with a pessimistic lock, the database holds a lock on it until your transaction commits or rolls back. Any other transaction that tries to lock or update the same row waits. On PostgreSQL, MySQL and Oracle JPA emits SELECT ... FOR UPDATE. This is a database feature, not a Hibernate trick, which means the lock is only as long as your transaction. If you are outside a transaction, a pessimistic lock does nothing useful, and Hibernate throws TransactionRequiredException.
The lock modes you will use are:
| Mode | SQL on PostgreSQL | Meaning |
|---|---|---|
PESSIMISTIC_WRITE | FOR UPDATE | Exclusive: blocks other readers using locks and writers |
PESSIMISTIC_READ | FOR SHARE | Shared: blocks writers, allows other shared readers |
PESSIMISTIC_FORCE_INCREMENT | FOR UPDATE plus version bump | Exclusive lock and increments @Version |
Databases differ in what they support; MySQL 8 and PostgreSQL support the shared form, others quietly use the exclusive one. In practice PESSIMISTIC_WRITE is the mode you reach for.
The stock example
package dev.javahacks.inventory;
import jakarta.persistence.*;
@Entity
public class StockItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String sku;
private int quantity;
protected StockItem() {}
public StockItem(String sku, int quantity) {
this.sku = sku;
this.quantity = quantity;
}
public void take(int amount) {
if (amount > quantity) {
throw new IllegalStateException("insufficient stock for " + sku);
}
this.quantity -= amount;
}
public int quantity() { return quantity; }
}With Spring Data JPA, ask for the lock on the repository method that loads the row:
package dev.javahacks.inventory;
import jakarta.persistence.LockModeType;
import jakarta.persistence.QueryHint;
import org.springframework.data.jpa.repository.*;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
public interface StockRepository extends JpaRepository<StockItem, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
@QueryHints(@QueryHint(name = "jakarta.persistence.lock.timeout", value = "3000"))
@Query("select s from StockItem s where s.sku = :sku")
Optional<StockItem> findBySkuForUpdate(@Param("sku") String sku);
}@Service
public class StockService {
private final StockRepository stock;
public StockService(StockRepository stock) {
this.stock = stock;
}
@Transactional
public void reserve(String sku, int amount) {
StockItem item = stock.findBySkuForUpdate(sku).orElseThrow();
item.take(amount); // dirty checking writes the update at commit
}
}Two concurrent calls to reserve("BK-1", 1) now serialise. The first thread's SELECT ... FOR UPDATE returns the row and holds the lock. The second thread's identical query blocks inside the database until the first transaction commits, then reads the committed quantity, so take sees the true value. The invariant, quantity never below zero, holds without any retry code. Turn on SQL logging and you can see the clause:
select s1_0.id,s1_0.quantity,s1_0.sku from stock_item s1_0 where s1_0.sku=? for no key updateOn PostgreSQL, Hibernate chooses for no key update for write locks on an entity that is not a foreign key target, a weaker lock that lets other transactions insert child rows. That detail varies by dialect and version, so check your own SQL log instead of assuming.
Lock timeouts
By default a waiting transaction waits forever, or for whatever the database's own lock wait timeout is. That is the setting that turns a slow transaction into an outage: all your pool connections end up waiting on one lock. Always set a timeout. The hint jakarta.persistence.lock.timeout takes milliseconds, and on supporting databases it becomes NOWAIT (a value of zero) or a session setting.
@QueryHints(@QueryHint(name = "jakarta.persistence.lock.timeout", value = "3000"))When the timeout expires, Hibernate throws LockTimeoutException (or PessimisticLockException if the database reports a different failure), and Spring translates both into PessimisticLockingFailureException subclasses, such as CannotAcquireLockException. Your service layer should catch it and decide: tell the caller to retry, or fail fast with a clear message.
try {
stockService.reserve(sku, 1);
} catch (PessimisticLockingFailureException e) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "item is being updated, retry shortly");
}SKIP LOCKED for work queues
A different use of pessimistic locking is claiming work. Several workers poll a table of jobs; each must take a job nobody else is processing. Locking the first row blocks the other workers behind it. SKIP LOCKED tells the database to ignore rows that are already locked and return the next free ones:
@Lock(LockModeType.PESSIMISTIC_WRITE)
@QueryHints(@QueryHint(name = "jakarta.persistence.lock.timeout", value = "-2")) // Hibernate: skip locked
@Query("select j from Job j where j.status = 'PENDING' order by j.createdAt")
List<Job> claimNext(Limit limit);The value -2 is Hibernate's marker for skip locked, and Limit is Spring Data's pagination argument (Spring Data 3.2 and later). Each worker runs this in a transaction, marks the returned jobs as RUNNING and commits, so the lock lasts only for the claim. PostgreSQL, MySQL 8 and Oracle support the clause; check that your database does before relying on it. This pattern is a lightweight queue with no broker, covered further in database deadlocks and retries.
Ordering and deadlocks
Pessimistic locking brings back the problem of lock ordering. If transaction one locks item A then item B, and transaction two locks B then A, they deadlock, exactly as in threads. The database detects the cycle after a short time and kills one transaction with an error. The cure is the same as in memory: acquire locks in a consistent order. For a transfer between two accounts, load both with a single query sorted by id:
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select a from Account a where a.id in :ids order by a.id")
List<Account> lockAll(@Param("ids") Collection<Long> ids);order by a.id is the important part: every transaction that needs these rows takes them in id order, so no cycle can form. Code that does hit a deadlock should retry the whole transaction, a pattern shown in handling database deadlocks in Java code.
Keep the lock short
A pessimistic lock is held until commit, so the transaction should do the minimum between locking and finishing. Do not call external services, send emails or wait for user input while holding one. Load, change, save, return. If you need to do slow work as part of the operation, do it before taking the lock or after committing. The isolation levels interact with this: under READ COMMITTED, which is the default on PostgreSQL, a locked read returns the latest committed version of the row, which is why the example above sees the true quantity; the options are described in SQL isolation levels and phantom reads.
Pessimistic or optimistic
| Pessimistic | Optimistic | |
|---|---|---|
| Conflict handling | Prevent: waiters block | Detect: loser gets an exception and retries |
| Cost with no conflict | A lock on every read | A version check, almost free |
| Cost with heavy conflict | Queueing, but each succeeds | Many retries, wasted work |
| Risk | Deadlocks, long waits, pool exhaustion | Retry storms |
| Best for | Hot rows, short critical updates, queues | Mostly independent updates, user edited forms |
A row that is updated by many requests per second, such as a stock count for a popular item, favours the pessimistic lock because optimistic retries would thrash. A customer profile edited by one person at a time favours the version column.
When this does not apply
Do not use a pessimistic lock to protect against two application instances doing the same job, if the job does not touch the locked row; that needs a distributed lock, covered in implementing a distributed lock. And if all you need is to decrement a counter safely, a single update stock set quantity = quantity - :n where sku = :sku and quantity >= :n is atomic, needs no lock and scales better; see handling concurrent updates in JPA. The primary reference is the Jakarta Persistence specification section on locking and the Hibernate user guide on locking.


