Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 39 ยท Transactions and Locking

Retries, Deadlocks and Concurrency Patterns

Build safe retry loops for optimistic lock failures and deadlocks, avoid deadlocks with lock ordering, and make operations idempotent in Hibernate applications.

Locks and versions turn concurrency bugs into exceptions. That is progress, but now the application must decide what to do with them. Some failures are transient: the same operation will succeed if you simply try again. This lesson shows how to retry correctly, how deadlocks arise and how to prevent them, and which habits keep concurrent code safe.

Hibernate is not available in the browser; the Hibernate and Spring snippets are read-only. The runnable programs implement the retry loop, a deadlock and its fix with plain Java threads and H2.

Which failures are retryable?

Exception Cause Retry?
OptimisticLockException / StaleObjectStateException someone changed the row since you read it yes, if you re-read and redo the whole unit of work
PessimisticLockException, LockTimeoutException waited too long for a lock maybe, after a pause
Deadlock (SQLState 40001, MySQL 1213, PostgreSQL 40P01) database killed your transaction yes
Serialization failure (40001) SERIALIZABLE detected a conflict yes
ConstraintViolationException unique key or foreign key usually no (for a unique-key race you may retry as "find or create")
LazyInitializationException, NullPointerException bug never

Retry the whole transaction, not the failed statement: after an exception the session state is unreliable. Open a new session, re-read the data, run the business logic again.

A retry helper

Java
public <T> T inTransactionWithRetry(Function<Session, T> work) {
    int attempt = 0;
    while (true) {
        try {
            return sessionFactory.fromTransaction(work);   // new session + transaction each attempt
        } catch (OptimisticLockException | LockTimeoutException | CannotAcquireLockException e) {
            if (++attempt >= 4) throw e;
            sleep(backoff(attempt));
        }
    }
}

Backoff should grow and include jitter (random variation) so competing workers do not retry in lockstep:

Java
static long backoff(int attempt) {
    long base = 20L << attempt;            // 40, 80, 160 ms
    return base + ThreadLocalRandom.current().nextLong(base);
}

With Spring, use Spring Retry (@Retryable) or Resilience4j around a method that is outside the @Transactional boundary. Retrying inside the same transaction cannot work, because the transaction is already rolled back.

Java Retry with backoff on a version conflict

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 number of conflicts varies from run to run, but the final count is always exact: the retries made the result correct.

Deadlocks

A deadlock needs two transactions and two resources taken in opposite order:

  1. T1 locks account A, T2 locks account B.
  2. T1 asks for B and waits; T2 asks for A and waits.
  3. Neither can proceed. The database picks a victim, rolls it back and reports an error.

The cure is lock ordering: always acquire locks in a global order. For a transfer between two accounts, lock the one with the smaller id first, regardless of which is the source:

Java
Long first = Math.min(fromId, toId), second = Math.max(fromId, toId);
Account a = session.find(Account.class, first, LockModeType.PESSIMISTIC_WRITE);
Account b = session.find(Account.class, second, LockModeType.PESSIMISTIC_WRITE);

A related source of deadlocks is Hibernate itself: it flushes statements in its own order (inserts, updates, deletes, by entity type). Setting hibernate.order_updates=true makes updates go in primary-key order, which removes many accidental deadlocks in batch jobs.

Java Opposite lock order causes a deadlock; ordered locks do not

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.

Concurrency patterns worth knowing

  • Idempotency keys. For operations a client may repeat (payments, order placement), store a unique key with the result. A second attempt hits the unique index and returns the stored outcome instead of doing the work twice.
  • Atomic statements. update ... set qty = qty - 1 where qty > 0 replaces read-modify-write for counters and stock.
  • Unique constraints as locks. "Insert, and on duplicate key, load the existing row" is race-free; "check, then insert" is not.
  • Small aggregates. The smaller the thing you lock or version, the fewer conflicts. A huge Customer aggregate with every order inside will conflict constantly.
  • Outbox. To publish a message after a commit, write it to an outbox table in the same transaction and let a poller send it (with SKIP LOCKED); this avoids "committed but message lost" races.
  • Read replicas lag. Do not read your own write from a replica inside one flow.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must a retry repeat after an OptimisticLockException?

    The data you based your change on is stale, so you must re-read and re-run the logic in a fresh session.
  2. 2. Why add jitter to retry backoff?

    Random variation spreads retries out and breaks lockstep conflicts.
  3. 3. How do you prevent a deadlock in a transfer between two accounts?

    A global lock order makes a circular wait impossible.
  4. 4. Which exception should you NOT retry?

    LazyInitializationException is a programming error; retrying will not fix it.

Summary

  • Retry only transient failures (version conflicts, deadlocks, serialization failures), as a whole new transaction, with exponential backoff and jitter.
  • Place retry logic outside the transactional boundary.
  • Prevent deadlocks with consistent lock order and ordered updates.
  • Use idempotency keys, atomic updates, unique constraints and small aggregates to make concurrency correct by design.

Next: Testing Hibernate Code