Skip to lesson

Optimistic locking with @Version vs pessimistic locks

Two clerks open the same product. One records a delivery, the other a sale, and the shop ends up with the wrong stock although both saves worked. No error is thrown anywhere.

The lost update: two clerks change the same stock

A lost update happens when two transactions read the same value, each computes a new value from it, and the later commit overwrites the earlier one without any error.

Clerk A books a delivery of 10 Redmi phones while clerk B records a sale of 3. Both read 40 first. Step through the race in plain Java, then see it in Spring.

Example 1 · StockClerkService.java: a lost update, forced with two latches

Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)

StockClerkService.javaJava
// src/main/java/com/shoplite/lab/locking/StockClerkService.javapackage com.shoplite.lab.locking;
import java.util.concurrent.CountDownLatch;import java.util.concurrent.TimeUnit;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
/** Two warehouse clerks change the same product's stock at the same time. */@Servicepublic class StockClerkService {
    private final ProductRepository products;
    public StockClerkService(ProductRepository products) {        this.products = products;    }
    /** Read, wait, write: the classic lost update. The latches only force the unlucky timing. */    @Transactional    public int adjustUnsafe(int productId, int delta, CountDownLatch bothRead, CountDownLatch waitBeforeWrite) {        Product product = products.findById(productId).orElseThrow();        int read = product.getStock();        bothRead.countDown();        await(bothRead);        await(waitBeforeWrite);        product.setStock(read + delta);        return read;    }
    /** SELECT ... FOR UPDATE: the second clerk waits here until the first one commits. */    @Transactional    public int adjustLocked(int productId, int delta, CountDownLatch locked, long holdMillis) {        Product product = products.findByIdForUpdate(productId).orElseThrow();        int read = product.getStock();        locked.countDown();        sleep(holdMillis);        product.setStock(read + delta);        return read;    }
    /** One atomic UPDATE: no read, no lost update, no oversell. */    @Transactional    public void buyOne(int productId) {        if (products.takeStock(productId, 1) == 0) {            throw new IllegalStateException("Product " + productId + " is sold out");        }    }
    private static void await(CountDownLatch latch) {        if (latch == null) {            return;        }        try {            latch.await(10, TimeUnit.SECONDS);        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }
    private static void sleep(long millis) {        try {            Thread.sleep(millis);        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }}
// src/main/java/com/shoplite/lab/locking/LostUpdateDemo.javapackage com.shoplite.lab.locking;
import java.util.concurrent.CountDownLatch;
import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;
@Component("lost-update")public class LostUpdateDemo implements LabDemo {
    private static final int REDMI = 1;
    private final StockClerkService clerks;    private final LabDb db;
    public LostUpdateDemo(StockClerkService clerks, LabDb db) {        this.clerks = clerks;        this.db = db;    }
    @Override    public void run() {        CountDownLatch bothRead = new CountDownLatch(2);        CountDownLatch firstCommitted = new CountDownLatch(1);
        Thread delivery = new Thread(() -> {            int read = clerks.adjustUnsafe(REDMI, +10, bothRead, null);            System.out.println("Clerk A read " + read + ", wrote " + (read + 10) + " (delivery of 10)");            firstCommitted.countDown();        });        Thread sale = new Thread(() -> {            int read = clerks.adjustUnsafe(REDMI, -3, bothRead, firstCommitted);            System.out.println("Clerk B read " + read + ", wrote " + (read - 3) + " (sale of 3)");        });        delivery.start();        sale.start();        join(delivery, sale);        System.out.println("Expected 40 + 10 - 3 = 47, stock in MySQL: " + db.stock(REDMI));    }
    static void join(Thread... threads) {        for (Thread t : threads) {            try {                t.join();            } catch (InterruptedException e) {                Thread.currentThread().interrupt();            }        }    }}
Sample output
$ java -jar target/tx-lab-0.1.0.jar --demo=lost-update --logging.level.org.hibernate.SQL=DEBUG
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=?
DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=?
Clerk A read 40, wrote 50 (delivery of 10)
DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=?
Clerk B read 40, wrote 37 (sale of 3)
Expected 40 + 10 - 3 = 47, stock in MySQL: 37

What this code does

  • Both clerks read 40 inside their own transactions. The latches only make the unlucky order certain: B waits until A has committed 50, then writes the 37 it computed from its old read.
  • Two plain UPDATEs, no error, and the delivery of 10 is lost: 37 instead of 47.

No exception is thrown: the database simply stores the last write. Hibernate's UPDATE sends every column by default, so the same thing happens to a price edited by one admin while another admin edits the name.

Transactions alone do not stop this. MySQL's default REPEATABLE READ gives each transaction a stable view of what it read, but a plain SELECT takes no lock, so both clerks happily read 40.

Trace the code

Two clerks, one stock

public class LostUpdate {
public static void main(String[] args) {
int stock = 40;
int readByA = stock;
int readByB = stock;
stock = readByA + 10;
stock = readByB - 3;
System.out.println("Stock: " + stock);
}
}

Variables

stock
40

Output

(nothing printed yet)

Line 3The shop has 40 Redmi phones in stock.

Step 1 of 6

@Version: the version check in the UPDATE

Optimistic locking assumes clashes are rare and checks for them only when writing, using a version number stored in the row.

Mark a numeric field with @Version, and Hibernate checks it on every UPDATE.

Product.javaJava
@Entity@Table(name = "products")public class Product {    ...    @Version    @Column(nullable = false)    private int version;   // Hibernate adds 1 on every UPDATE and checks it in the WHERE
    public int getVersion() {        return version;    }}

Example 2 · OptimisticClerkService.java: the same race with @Version

Runs in: the lock-lab practice project (Spring Boot 4.1, ShopLite database with a version column)

OptimisticClerkService.javaJava
// src/main/java/com/shoplite/lab/optimistic/OptimisticClerkService.javapackage com.shoplite.lab.optimistic;
import java.util.concurrent.CountDownLatch;import java.util.concurrent.TimeUnit;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Servicepublic class OptimisticClerkService {
    private final ProductRepository products;
    public OptimisticClerkService(ProductRepository products) {        this.products = products;    }
    /** The same read-wait-write code as the lost-update demo. Only Product changed: it has @Version now. */    @Transactional    public int adjust(int productId, int delta, CountDownLatch bothRead, CountDownLatch waitBeforeWrite) {        Product product = products.findById(productId).orElseThrow();        int read = product.getStock();        if (bothRead != null) {            bothRead.countDown();        }        await(bothRead);        await(waitBeforeWrite);        product.setStock(read + delta);        return read;    }
    private static void await(CountDownLatch latch) {        if (latch == null) {            return;        }        try {            latch.await(10, TimeUnit.SECONDS);        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }}
// src/main/java/com/shoplite/lab/optimistic/OptimisticDemo.javapackage com.shoplite.lab.optimistic;
import java.util.concurrent.CountDownLatch;
import org.springframework.orm.ObjectOptimisticLockingFailureException;import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;
@Component("optimistic")public class OptimisticDemo implements LabDemo {
    private static final int REDMI = 1;
    private final OptimisticClerkService clerks;    private final LabDb db;
    public OptimisticDemo(OptimisticClerkService clerks, LabDb db) {        this.clerks = clerks;        this.db = db;    }
    @Override    public void run() {        CountDownLatch bothRead = new CountDownLatch(2);        CountDownLatch firstCommitted = new CountDownLatch(1);
        Thread delivery = new Thread(() -> {            int read = clerks.adjust(REDMI, +10, bothRead, null);            System.out.println("Clerk A read " + read + ", wrote " + (read + 10));            firstCommitted.countDown();        });        Thread sale = new Thread(() -> {            try {                clerks.adjust(REDMI, -3, bothRead, firstCommitted);            } catch (ObjectOptimisticLockingFailureException e) {                System.out.println("Clerk B failed: " + e.getMessage());                int read = clerks.adjust(REDMI, -3, null, null);                System.out.println("Clerk B retried: read " + read + ", wrote " + (read - 3));            }        });        delivery.start();        sale.start();        join(delivery);        join(sale);        System.out.println("Stock in MySQL: " + db.stock(REDMI));    }
    private static void join(Thread t) {        try {            t.join();        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }}
Sample output
$ java -jar target/lock-lab-0.1.0.jar --demo=optimistic --logging.level.org.hibernate.SQL=DEBUG
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock,p1_0.version from products p1_0 where p1_0.product_id=?
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock,p1_0.version from products p1_0 where p1_0.product_id=?
DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=?,version=? where product_id=? and version=?
Clerk A read 40, wrote 50
DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=?,version=? where product_id=? and version=?
Clerk B failed: Unexpected row count (expected row count 1 but was 0) [update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=?,version=? where product_id=? and version=?] for entity [com.shoplite.product.Product with id '1']
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock,p1_0.version from products p1_0 where p1_0.product_id=?
DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=?,version=? where product_id=? and version=?
Clerk B retried: read 50, wrote 47
Stock in MySQL: 47

What this code does

  • The UPDATE now ends where product_id=? and version=?. A's matched version 0 and moved it to 1; B's still said version 0, matched no row, and Hibernate reported "Unexpected row count (expected row count 1 but was 0)", which Spring wraps as ObjectOptimisticLockingFailureException.
  • B retried in a new transaction, read 50 and wrote 47: nothing was lost. The retry is your code; Spring does not retry for you.

Example 3 · ProductPriceService.java: a stale version becomes 409 Conflict

Runs in: the lock-lab practice project (Spring Boot 4.1, ShopLite database with a version column)

ProductPriceService.javaJava
// src/main/java/com/shoplite/lab/web/ProductPriceService.javapackage com.shoplite.lab.web;
import java.math.BigDecimal;
import org.springframework.orm.ObjectOptimisticLockingFailureException;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Servicepublic class ProductPriceService {
    private final ProductRepository products;
    public ProductPriceService(ProductRepository products) {        this.products = products;    }
    @Transactional(readOnly = true)    public ProductPriceResponse get(int id) {        return toResponse(products.findById(id).orElseThrow());    }
    @Transactional    public ProductPriceResponse changePrice(int id, BigDecimal newPrice, int versionSeenByClient) {        Product product = products.findById(id).orElseThrow();        if (product.getVersion() != versionSeenByClient) {            throw new ObjectOptimisticLockingFailureException(Product.class, id);        }        product.setPrice(newPrice);        products.flush();        return toResponse(product);    }
    private static ProductPriceResponse toResponse(Product p) {        return new ProductPriceResponse(p.getId(), p.getName(), p.getPrice(), p.getVersion());    }}
// src/main/java/com/shoplite/lab/web/LockingExceptionHandler.javapackage com.shoplite.lab.web;
import java.net.URI;
import org.springframework.dao.OptimisticLockingFailureException;import org.springframework.http.HttpStatus;import org.springframework.http.ProblemDetail;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvicepublic class LockingExceptionHandler {
    @ExceptionHandler(OptimisticLockingFailureException.class)    public ProblemDetail editConflict(OptimisticLockingFailureException e) {        ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT,                "Someone else changed this item after you opened it. Reload it and try again.");        problem.setType(URI.create("https://shoplite.example/problems/edit-conflict"));        problem.setTitle("Edit conflict");        return problem;    }}
package com.shoplite.lab.web;
import java.math.BigDecimal;
/** The new price, and the version the admin saw when the edit screen opened. */public record PriceChangeRequest(BigDecimal price, int version) {}
Sample output
$ curl -s http://localhost:8080/api/v1/products/6
{"id":6,"name":"boAt Airdopes 141","price":1299.00,"version":0}

$ curl -i -s -X PATCH http://localhost:8080/api/v1/products/6 -H "Content-Type: application/json" -d '{"price":1199.00,"version":0}'
HTTP/1.1 200
Content-Type: application/json
Content-Length: 63
Date: Fri, 16 Oct 2026 07:04:10 GMT

{"id":6,"name":"boAt Airdopes 141","price":1199.00,"version":1}

$ curl -i -s -X PATCH http://localhost:8080/api/v1/products/6 -H "Content-Type: application/json" -d '{"price":1249.00,"version":0}'
HTTP/1.1 409
Content-Type: application/problem+json
Transfer-Encoding: chunked
Date: Fri, 16 Oct 2026 07:04:10 GMT

{"detail":"Someone else changed this item after you opened it. Reload it and try again.","instance":"/api/v1/products/6","status":409,"title":"Edit conflict","type":"https://shoplite.example/problems/edit-conflict"}

What this code does

  • Two admins opened product 6 at version 0. The first PATCH saved and returned version 1 (flush() ran the UPDATE early so the response shows it). The second still sent version 0 and got 409 instead of silently overwriting 1199.00.
  • The handler maps every OptimisticLockingFailureException, so the check in the service and a real version clash at commit end in the same 409. edit-conflict is a new problem kind; adding one is not a breaking change to the v1 contract.
  • The lab sorts ProblemDetail fields alphabetically (Jackson 3's default); ShopLite sets spring.jackson.mapper.sort-properties-alphabetically=false to keep the contract's order.

Hibernate adds version = version + 1 to every UPDATE and AND version = ? (the version it read) to the WHERE. If another transaction changed the row first, zero rows match, and Spring throws ObjectOptimisticLockingFailureException (a subclass of OptimisticLockingFailureException). The column must exist in the table: ShopLite's Section 12 schema has none, so lock-lab adds ALTER TABLE products ADD COLUMN version INT NOT NULL DEFAULT 0. In ShopLite you would add it with a migration in the Flyway module, and ddl-auto=validate would check it.

For a web app the version travels with the data: the edit screen gets version: 0, the PATCH sends it back, and a stale version means "someone saved after you opened this". Map the exception to 409 Conflict with a ProblemDetail so the client can reload and try again.

Pessimistic locks: PESSIMISTIC_WRITE and SELECT ... FOR UPDATE

Pessimistic locking locks the row when you read it, with SELECT ... FOR UPDATE, so other transactions wait instead of failing later.

Put @Lock(LockModeType.PESSIMISTIC_WRITE) on a query method and the row is locked as it is read. The example runs two clerks, then adds a timeout.

Example 4 · ProductRepository.java: PESSIMISTIC_WRITE, NOWAIT and timeouts

Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)

ProductRepository.javaJava
// src/main/java/com/shoplite/product/ProductRepository.javapackage com.shoplite.product;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.data.jpa.repository.Lock;import org.springframework.data.jpa.repository.Modifying;import org.springframework.data.jpa.repository.Query;import org.springframework.data.jpa.repository.QueryHints;import org.springframework.data.repository.query.Param;
import jakarta.persistence.LockModeType;import jakarta.persistence.QueryHint;
public interface ProductRepository extends JpaRepository<Product, Integer> {
    /** Only the stock number. A scalar query always goes to the database (no entity cache). */    @Query("select p.stock from Product p where p.id = :id")    int findStockById(@Param("id") Integer id);
    /** SELECT ... FOR UPDATE: other transactions wait until this one ends. */    @Lock(LockModeType.PESSIMISTIC_WRITE)    @Query("select p from Product p where p.id = :id")    Optional<Product> findByIdForUpdate(@Param("id") Integer id);
    /** Same lock, but give up at once if another transaction holds it. */    @Lock(LockModeType.PESSIMISTIC_WRITE)    @QueryHints(@QueryHint(name = "jakarta.persistence.lock.timeout", value = "0"))    @Query("select p from Product p where p.id = :id")    Optional<Product> findByIdForUpdateNoWait(@Param("id") Integer id);
    /** Same lock, waiting at most 2 seconds. */    @Lock(LockModeType.PESSIMISTIC_WRITE)    @QueryHints(@QueryHint(name = "jakarta.persistence.lock.timeout", value = "2000"))    @Query("select p from Product p where p.id = :id")    Optional<Product> findByIdForUpdateWait2s(@Param("id") Integer id);
    /** Check and change in ONE statement. Returns 1 when the stock was taken, 0 when there was not enough. */    @Modifying    @Query("update Product p set p.stock = p.stock - :quantity where p.id = :id and p.stock >= :quantity")    int takeStock(@Param("id") Integer id, @Param("quantity") int quantity);}
// src/main/java/com/shoplite/lab/locking/PessimisticDemo.javapackage com.shoplite.lab.locking;
import java.util.concurrent.CountDownLatch;
import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;
@Component("pessimistic")public class PessimisticDemo implements LabDemo {
    private static final int REDMI = 1;
    private final StockClerkService clerks;    private final LabDb db;
    public PessimisticDemo(StockClerkService clerks, LabDb db) {        this.clerks = clerks;        this.db = db;    }
    @Override    public void run() {        CountDownLatch aLocked = new CountDownLatch(1);
        Thread delivery = new Thread(() -> {            int read = clerks.adjustLocked(REDMI, +10, aLocked, 1000);            System.out.println("Clerk A read " + read + ", wrote " + (read + 10));        });        Thread sale = new Thread(() -> {            await(aLocked);            long start = System.nanoTime();            int read = clerks.adjustLocked(REDMI, -3, new CountDownLatch(1), 0);            long waited = (System.nanoTime() - start) / 1_000_000;            System.out.println("Clerk B read " + read + ", wrote " + (read - 3) + " after waiting about "                    + (waited / 100) * 100 + " ms");        });        delivery.start();        sale.start();        LostUpdateDemo.join(delivery, sale);        System.out.println("Expected 47, stock in MySQL: " + db.stock(REDMI));    }
    private static void await(CountDownLatch latch) {        try {            latch.await();        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }}
// src/main/java/com/shoplite/lab/locking/LockTimeoutService.javapackage com.shoplite.lab.locking;
import java.util.concurrent.CountDownLatch;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.product.ProductRepository;
@Servicepublic class LockTimeoutService {
    private final ProductRepository products;
    public LockTimeoutService(ProductRepository products) {        this.products = products;    }
    @Transactional    public void holdLock(int productId, CountDownLatch locked, long millis) throws InterruptedException {        products.findByIdForUpdate(productId).orElseThrow();        locked.countDown();        Thread.sleep(millis);    }
    @Transactional    public void lockNoWait(int productId) {        products.findByIdForUpdateNoWait(productId).orElseThrow();    }
    @Transactional    public void lockWait2s(int productId) {        products.findByIdForUpdateWait2s(productId).orElseThrow();    }}
Sample output (timings differ)
$ java -jar target/tx-lab-0.1.0.jar --demo=pessimistic --logging.level.org.hibernate.SQL=DEBUG
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? for update of p1_0
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? for update of p1_0
DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=?
Clerk A read 40, wrote 50
DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=?
Clerk B read 50, wrote 47 after waiting about 1100 ms
Expected 47, stock in MySQL: 47

$ java -jar target/tx-lab-0.1.0.jar --demo=lock-timeout --logging.level.org.hibernate.SQL=DEBUG
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? for update of p1_0
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? for update of p1_0 nowait
WARN  org.hibernate.orm.jdbc.error : HHH000247: ErrorCode: 3572, SQLState: HY000
WARN  org.hibernate.orm.jdbc.error : Statement aborted because lock(s) could not be acquired immediately and NOWAIT is set.
timeout 0:    CannotAcquireLockException: Statement aborted because lock(s) could not be acquired immediately and NOWAIT is set.
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? for update of p1_0
timeout 2000: got the lock after about 3200 ms

$ java -jar target/tx-lab-0.1.0.jar --demo=lock-timeout "--spring.datasource.hikari.connection-init-sql=SET SESSION innodb_lock_wait_timeout = 2"
WARN  org.hibernate.orm.jdbc.error : HHH000247: ErrorCode: 3572, SQLState: HY000
WARN  org.hibernate.orm.jdbc.error : Statement aborted because lock(s) could not be acquired immediately and NOWAIT is set.
timeout 0:    CannotAcquireLockException: Statement aborted because lock(s) could not be acquired immediately and NOWAIT is set.
WARN  org.hibernate.orm.jdbc.error : HHH000247: ErrorCode: 1205, SQLState: 40001
WARN  org.hibernate.orm.jdbc.error : Lock wait timeout exceeded; try restarting transaction
timeout 2000: CannotAcquireLockException after about 2000 ms: Lock wait timeout exceeded; try restarting transaction

What this code does

  • First run: both clerks sent ... for update of p1_0. B's SELECT waited about a second until A committed 50, then read 50 and wrote 47. No lost update.
  • Second run: while another transaction held the lock, timeout 0 became nowait and failed at once; the 2000 ms hint was not applied on MySQL, so that call simply waited for the lock.
  • Third run: with innodb_lock_wait_timeout = 2 set on each connection, MySQL gave up after 2 seconds with "Lock wait timeout exceeded". LockTimeoutDemo holds the lock for 4 seconds in another thread.

Hibernate 7 on MySQL sends SELECT ... FOR UPDATE OF p1_0. Another transaction asking for the same lock waits until the first commits or rolls back, and then reads the fresh value. Waiting needs a limit: the JPA hint jakarta.persistence.lock.timeout = 0 becomes FOR UPDATE ... NOWAIT and fails at once with CannotAcquireLockException. Other values were not applied by Hibernate on MySQL in our run; MySQL's own limit is innodb_lock_wait_timeout (50 seconds by default), which you can lower per connection, for example with spring.datasource.hikari.connection-init-sql.

A lock lives as long as the transaction. Keep locking transactions short: no HTTP calls, no sleeping clerks, no user input while a row is locked.

An atomic alternative for stock: UPDATE ... WHERE stock >= :qty

An atomic update checks and changes a value in one SQL statement, so no other transaction can slip in between.

UPDATE products SET stock = stock - :quantity WHERE product_id = :id AND stock >= :quantity checks and changes together. Eight buyers go for five laptops.

Example 5 · AtomicUpdateDemo.java: 8 buyers, 5 laptops, one UPDATE each

Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)

AtomicUpdateDemo.javaJava
// src/main/java/com/shoplite/lab/locking/AtomicUpdateDemo.javapackage com.shoplite.lab.locking;
import java.util.ArrayList;import java.util.List;import java.util.concurrent.CountDownLatch;import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;
@Component("atomic")public class AtomicUpdateDemo implements LabDemo {
    private static final int HP_VICTUS = 5;   // 5 in stock    private static final int BUYERS = 8;
    private final StockClerkService clerks;    private final LabDb db;
    public AtomicUpdateDemo(StockClerkService clerks, LabDb db) {        this.clerks = clerks;        this.db = db;    }
    @Override    public void run() {        CountDownLatch go = new CountDownLatch(1);        AtomicInteger sold = new AtomicInteger();        AtomicInteger soldOut = new AtomicInteger();        List<Thread> buyers = new ArrayList<>();        for (int i = 0; i < BUYERS; i++) {            Thread t = new Thread(() -> {                try {                    go.await();                    clerks.buyOne(HP_VICTUS);                    sold.incrementAndGet();                } catch (IllegalStateException e) {                    soldOut.incrementAndGet();                } catch (InterruptedException e) {                    Thread.currentThread().interrupt();                }            });            buyers.add(t);            t.start();        }        go.countDown();   // all 8 buyers press "Buy" at the same moment        LostUpdateDemo.join(buyers.toArray(new Thread[0]));        System.out.println(BUYERS + " buyers, 5 laptops: sold " + sold.get() + ", told sold out " + soldOut.get()                + ", stock in MySQL: " + db.stock(HP_VICTUS));    }}
Sample output
$ java -jar target/tx-lab-0.1.0.jar --demo=atomic --logging.level.org.hibernate.SQL=DEBUG
DEBUG org.hibernate.SQL : update products p1_0 set stock=(p1_0.stock-?) where p1_0.product_id=? and p1_0.stock>=?
DEBUG org.hibernate.SQL : update products p1_0 set stock=(p1_0.stock-?) where p1_0.product_id=? and p1_0.stock>=?
DEBUG org.hibernate.SQL : update products p1_0 set stock=(p1_0.stock-?) where p1_0.product_id=? and p1_0.stock>=?
DEBUG org.hibernate.SQL : update products p1_0 set stock=(p1_0.stock-?) where p1_0.product_id=? and p1_0.stock>=?
DEBUG org.hibernate.SQL : update products p1_0 set stock=(p1_0.stock-?) where p1_0.product_id=? and p1_0.stock>=?
DEBUG org.hibernate.SQL : update products p1_0 set stock=(p1_0.stock-?) where p1_0.product_id=? and p1_0.stock>=?
DEBUG org.hibernate.SQL : update products p1_0 set stock=(p1_0.stock-?) where p1_0.product_id=? and p1_0.stock>=?
DEBUG org.hibernate.SQL : update products p1_0 set stock=(p1_0.stock-?) where p1_0.product_id=? and p1_0.stock>=?
8 buyers, 5 laptops: sold 5, told sold out 3, stock in MySQL: 0

What this code does

  • Each buyer calls buyOne from Example 1: takeStock(5, 1) sends update products ... set stock=(p1_0.stock-?) where p1_0.product_id=? and p1_0.stock>=? and checks the row count.
  • All 8 started together. Exactly 5 got a row count of 1, the other 3 got 0 and were told the laptop is sold out, and stock ended at 0, never below.

MySQL locks the row for the length of the statement, so two buyers can never both take the last unit. In Spring Data it is a @Modifying JPQL query that returns the number of changed rows: 1 means the units were taken, 0 means there were not enough. Like any write, it needs a surrounding transaction.

An atomic update bypasses the persistence context: a Product you loaded earlier in the same transaction still shows the old stock. Load it again, or use @Modifying(clearAutomatically = true), if you need the new value.

Predict the output

What does takeStock return?

It returns the number of rows the UPDATE changed.

Round 1 of 3

Product 5 has stock 2.

// stock of product 5 is 2
int rows = products.takeStock(5, 3);

Choosing, and deadlocks: lock in a fixed order

A deadlock is two transactions that each hold a lock the other one needs, so neither can go on.

Pick the tool by how often clashes happen and what the user should see. The last example locks two products in opposite orders, then in id order.

Example 6 · BasketLockService.java: a deadlock, then the same code in id order

Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)

BasketLockService.javaJava
// src/main/java/com/shoplite/lab/locking/BasketLockService.javapackage com.shoplite.lab.locking;
import java.util.List;import java.util.concurrent.CyclicBarrier;import java.util.concurrent.TimeUnit;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
/** Locks every product of a basket, one after the other, then takes one unit of each. */@Servicepublic class BasketLockService {
    private final ProductRepository products;
    public BasketLockService(ProductRepository products) {        this.products = products;    }
    @Transactional    public void buyBasket(List<Integer> productIdsInLockOrder, CyclicBarrier afterFirstLock) throws Exception {        boolean first = true;        for (int id : productIdsInLockOrder) {            Product product = products.findByIdForUpdate(id).orElseThrow();            product.setStock(product.getStock() - 1);            if (first) {                first = false;                try {                    afterFirstLock.await(2, TimeUnit.SECONDS);                } catch (Exception timeout) {                }            }        }    }}
// src/main/java/com/shoplite/lab/locking/DeadlockDemo.javapackage com.shoplite.lab.locking;
import java.util.List;import java.util.concurrent.CyclicBarrier;
import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;
@Component("deadlock")public class DeadlockDemo implements LabDemo {
    private final BasketLockService baskets;    private final LabDb db;    private final boolean sorted;
    public DeadlockDemo(BasketLockService baskets, LabDb db, @Value("${sorted:false}") boolean sorted) {        this.baskets = baskets;        this.db = db;        this.sorted = sorted;    }
    @Override    public void run() {        CyclicBarrier afterFirstLock = new CyclicBarrier(2);        List<Integer> basketA = List.of(1, 6);        List<Integer> basketB = sorted ? List.of(1, 6) : List.of(6, 1);        Thread a = new Thread(() -> buy("A", basketA, afterFirstLock));        Thread b = new Thread(() -> buy("B", basketB, afterFirstLock));        a.start();        b.start();        LostUpdateDemo.join(a, b);        System.out.println("Stock now: Redmi " + db.stock(1) + ", Airdopes " + db.stock(6));    }
    private void buy(String buyer, List<Integer> basket, CyclicBarrier barrier) {        try {            baskets.buyBasket(basket, barrier);            System.out.println("Buyer " + buyer + " " + basket + ": done");        } catch (Exception e) {            System.out.println("Buyer " + buyer + " " + basket + ": " + e.getClass().getSimpleName()                    + ": " + LockTimeoutDemo.rootMessage(e));        }    }}
Sample output (which buyer loses can differ)
$ java -jar target/tx-lab-0.1.0.jar --demo=deadlock --logging.level.org.hibernate.SQL=DEBUG
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? for update of p1_0
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? for update of p1_0
DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=?
DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=?
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? for update of p1_0
DEBUG org.hibernate.SQL : select p1_0.product_id,p1_0.is_active,p1_0.category_id,p1_0.name,p1_0.price,p1_0.sku,p1_0.stock from products p1_0 where p1_0.product_id=? for update of p1_0
DEBUG org.hibernate.SQL : update products set is_active=?,category_id=?,name=?,price=?,sku=?,stock=? where product_id=?
Buyer B [6, 1]: done
WARN  org.hibernate.orm.jdbc.error : HHH000247: ErrorCode: 1213, SQLState: 40001
WARN  org.hibernate.orm.jdbc.error : Deadlock found when trying to get lock; try restarting transaction
Buyer A [1, 6]: CannotAcquireLockException: Deadlock found when trying to get lock; try restarting transaction
Stock now: Redmi 39, Airdopes 119

$ java -jar target/tx-lab-0.1.0.jar --demo=deadlock --sorted=true
Buyer B [1, 6]: done
Buyer A [1, 6]: done
Stock now: Redmi 38, Airdopes 118

What this code does

  • First run: A locked product 1 and B locked product 6, then each asked for the other one. MySQL found the cycle, rolled one buyer back with "Deadlock found when trying to get lock" and let the other finish: only one unit left each product.
  • Second run: both baskets lock 1 before 6, so B simply waits for A; both finish and both units are sold. ShopLite's OrderService.place sorts items by product id for this reason.

Which tool to pick:

  • Rare clashes, a human editing a form (product details, prices): optimistic @Version, 409 on conflict, the client reloads.
  • A hot row many requests change at once (stock of a sale item): an atomic UPDATE, or a pessimistic lock if you must read and decide in Java.
  • Several rows locked in one transaction (an order with many products): lock them in a fixed order, such as by id.
  • Retry only optimistic or deadlock failures, a few times, each in a new transaction.

MySQL detects a deadlock at once, rolls one transaction back with "Deadlock found when trying to get lock; try restarting transaction" (CannotAcquireLockException in Spring) and lets the other finish. Locking rows in the same order everywhere makes a deadlock impossible.

Next step

Check your understanding

12 quick questions