Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 39 ยท Transactions and Locking

Pessimistic Locking

Use Hibernate pessimistic locks - PESSIMISTIC_WRITE, PESSIMISTIC_READ, lock timeouts and SKIP LOCKED - to serialize access to hot rows, and learn when optimistic locking is better.

Optimistic locking detects conflicts when you save. When conflicts are frequent (a ticket counter, a bank balance, a job queue) failing and retrying wastes work. Pessimistic locking takes a database lock when the row is read, so other transactions that want the same row wait their turn. The database does the queuing for you.

Hibernate is not available in the browser, so the Hibernate calls are read-only. The runnable program uses H2's select ... for update with real threads to show the waiting behaviour that Hibernate triggers.

Lock modes in Hibernate

Java
Account acc = session.find(Account.class, 1L, LockModeType.PESSIMISTIC_WRITE);
acc.withdraw(100);          // nobody else can change or lock this row until we commit

or with a query:

Java
Account acc = session.createQuery("from Account a where a.id = :id", Account.class)
    .setParameter("id", 1L)
    .setLockMode(LockModeType.PESSIMISTIC_WRITE)
    .getSingleResult();
Mode SQL (typical) Meaning
PESSIMISTIC_READ for share / lock in share mode others may read and share-lock, nobody may write
PESSIMISTIC_WRITE for update exclusive: others wait to read-for-update or write
PESSIMISTIC_FORCE_INCREMENT for update + version bump write lock that also increments @Version

The exact SQL depends on the dialect; some databases do not support a lock on a read at all and Hibernate falls back to the strongest available. Locks last until the transaction ends, so the lock only makes sense inside a transaction.

Locks apply to the rows of the entity table. With join fetch of several tables, you can name the tables to lock with the jakarta.persistence.lock.scope hint (EXTENDED locks collections and join tables too).

Java select ... for update makes a second thread wait

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The second thread cannot read the row for update until the first one commits, so it sees the booking and backs off. No lost update, no retry loop, but the second user waited.

Timeouts and NOWAIT

An unbounded wait is dangerous. Set a timeout in milliseconds:

Java
session.find(Account.class, 1L, LockModeType.PESSIMISTIC_WRITE,
    Map.of("jakarta.persistence.lock.timeout", 2000));

Special values: 0 means NOWAIT (fail at once if locked, on databases that support it), and -2 in Hibernate means SKIP LOCKED. When the timeout expires Hibernate throws PessimisticLockException or LockTimeoutException. Catch it and either show "busy, try again" or retry later.

SKIP LOCKED for work queues

Several workers polling the same table should not fight for the same row. SKIP LOCKED hands each worker rows nobody else holds:

Java
List<Job> batch = session.createQuery("from Job j where j.status = 'NEW' order by j.id", Job.class)
    .setMaxResults(10)
    .setLockMode(LockModeType.PESSIMISTIC_WRITE)
    .setHint("jakarta.persistence.lock.timeout", -2)   // SKIP LOCKED
    .getResultList();
batch.forEach(Job::start);

This gives a simple, correct job queue on a plain table (PostgreSQL, MySQL 8, Oracle, SQL Server all support the idea).

Costs and dangers

  • Waiting: long transactions with locks form queues; throughput collapses.
  • Deadlocks: two transactions lock rows in opposite order and wait for each other forever. The database detects it and kills one. Always lock rows in a consistent order (for example ascending id).
  • Connection hogging: a transaction holding a lock holds a pooled connection too.
  • Gap locks: in MySQL REPEATABLE_READ, locking reads can lock ranges and block inserts.

Optimistic or pessimistic?

Question Prefer
Conflicts are rare, user edits take minutes optimistic
Conflicts are common and work is expensive to redo pessimistic
Single hot row (balance, counter) pessimistic, or an atomic update ... set x = x + 1
Queue consumers pessimistic with SKIP LOCKED
Reads far outnumber writes optimistic

Often the simplest tool is neither: a single atomic statement such as update stock set qty = qty - 1 where id = ? and qty > 0 needs no lock in Java and is correct under concurrency. Check the update count to know whether it succeeded.

Java Atomic update instead of read-modify-write

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which lock mode normally produces SELECT ... FOR UPDATE?

    PESSIMISTIC_WRITE takes an exclusive row lock. PESSIMISTIC_READ maps to a shared lock where available.
  2. 2. When is a pessimistic lock released?

    Database row locks live until the end of the transaction.
  3. 3. What does SKIP LOCKED let a worker do?

    It is ideal for job queues: each worker gets different unlocked rows without waiting.
  4. 4. How do you avoid deadlocks between transactions that lock several rows?

    If everybody acquires locks in the same order, a circular wait cannot form.

Summary

  • Pessimistic modes take database row locks at read time (for update, for share) that last until the transaction ends.
  • Use timeouts, NOWAIT or SKIP LOCKED instead of unbounded waits; it suits hot rows and job queues.
  • Keep locked transactions short and lock in a consistent order to avoid deadlocks.
  • An atomic conditional update often beats both locking styles.

Next: Retries, Deadlocks and Concurrency Patterns