Skip to lesson

Preventing overselling with SELECT ... FOR UPDATE

When two customers press "Pay" for the last iPhone at the same moment, both can see "1 in stock" and both get an order. How do you stop that, and what do you do when locks collide?

Two threads buying the last item: the race reproduced

A race condition is a bug whose result depends on the timing of two threads. The classic one is read, decide, write: read the stock, check it in Java, write the new value.

In Example 1 two threads, Asha and Ravi, each open a connection and run read, decide, write on the stock of the last iPhone.

Example 1 · The race: two orders for the last iPhone

Runs in: a Maven project with the MySQL driver and the ShopLite database

OversellRaceDemo.javaJava
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.List;import java.util.concurrent.CopyOnWriteArrayList;import java.util.concurrent.CyclicBarrier;
public class OversellRaceDemo {    static final int IPHONE = 3;    static final List<Integer> demoOrders = new CopyOnWriteArrayList<>();
    static Connection connect() throws SQLException {        return DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));    }
    static int readStock(Connection conn) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement("SELECT stock FROM products WHERE product_id = ?")) {            ps.setInt(1, IPHONE);            try (ResultSet rs = ps.executeQuery()) {                rs.next();                return rs.getInt("stock");            }        }    }
    static void writeStock(Connection conn, int value) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement("UPDATE products SET stock = ? WHERE product_id = ?")) {            ps.setInt(1, value);            ps.setInt(2, IPHONE);            ps.executeUpdate();        }    }
    static void saveOrder(Connection conn, int customerId, int addressId) throws SQLException {        int orderId;        try (PreparedStatement ps = conn.prepareStatement(                "INSERT INTO orders (customer_id, address_id) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS)) {            ps.setInt(1, customerId);            ps.setInt(2, addressId);            ps.executeUpdate();            try (ResultSet keys = ps.getGeneratedKeys()) {                keys.next();                orderId = keys.getInt(1);            }        }        try (PreparedStatement ps = conn.prepareStatement(                "INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (?, ?, 1, ?)")) {            ps.setInt(1, orderId);            ps.setInt(2, IPHONE);            ps.setBigDecimal(3, new BigDecimal("69900.00"));            ps.executeUpdate();        }        demoOrders.add(orderId);    }
    static void waitForOther(CyclicBarrier barrier) {        try {            barrier.await();        } catch (Exception e) {            throw new IllegalStateException(e);        }    }
    // BUG: read the stock, decide in Java, write the new value    static String buy(String name, int customerId, int addressId, CyclicBarrier bothHaveRead) {        try (Connection conn = connect()) {            conn.setAutoCommit(false);            try {                int stock = readStock(conn);                waitForOther(bothHaveRead);          // makes the unlucky timing happen every run                if (stock < 1) {                    conn.rollback();                    return name + ": out of stock";                }                writeStock(conn, stock - 1);                saveOrder(conn, customerId, addressId);                conn.commit();                return name + ": order placed (saw stock " + stock + ")";            } catch (SQLException | RuntimeException e) {                conn.rollback();                return name + ": failed, " + e.getMessage();            }        } catch (SQLException e) {            return name + ": no connection, " + e.getMessage();        }    }
    public static void main(String[] args) throws Exception {        try (Connection conn = connect()) {            writeStock(conn, 1);                     // the last iPhone        }
        CyclicBarrier bothHaveRead = new CyclicBarrier(2);        List<String> results = new CopyOnWriteArrayList<>();        Thread asha = new Thread(() -> results.add(buy("Asha", 1, 1, bothHaveRead)));        Thread ravi = new Thread(() -> results.add(buy("Ravi", 2, 3, bothHaveRead)));        asha.start();        ravi.start();        asha.join();        ravi.join();
        results.stream().sorted().forEach(System.out::println);        try (Connection conn = connect()) {            System.out.println("Orders for the last iPhone: " + demoOrders.size()                    + ", stock now: " + readStock(conn));
            try (PreparedStatement ps = conn.prepareStatement("DELETE FROM orders WHERE order_id = ?")) {                for (int orderId : demoOrders) {                    ps.setInt(1, orderId);                    ps.executeUpdate();                }            }            writeStock(conn, 8);        }    }}
Sample output
Asha: order placed (saw stock 1)
Ravi: order placed (saw stock 1)
Orders for the last iPhone: 2, stock now: 0

What this code does

  • Both buyers read stock 1 with a plain SELECT, wait at the barrier, then each writes stock - 1 computed in Java (0) and saves an order. Two orders exist for one phone.
  • Ravi's UPDATE waits for Asha's row lock, but when it runs it writes the value he computed from his stale read. The program deletes the two demo orders and puts the stock back to 8.

Both threads read stock 1, both decide "enough", both write 0 and both save an order: two orders for one phone, stock 0, and no error anywhere. A CyclicBarrier (from the Concurrency section) makes both threads read before either writes, so the unlucky timing happens on every run instead of once in a thousand. Ravi's UPDATE waited for Asha's lock, but then wrote the value he had computed from his old read.

Predict the output

How many orders get through?

The stock is 1. Both buyers read before either one writes.

Each buyer reads with a plain SELECT, then writes the value computed in Java.

int stock = readStock(conn); // 1
if (stock >= 1) {
writeStock(conn, stock - 1); // 0
insertOrder(conn, customerId);
}
conn.commit();

SELECT ... FOR UPDATE locks the rows until commit

An exclusive lock is a lock taken by SELECT ... FOR UPDATE or by an UPDATE on a row. It stays until the transaction commits or rolls back, and other transactions that touch the row wait.

Example 2 starts both buyers together, but each reads with SELECT ... FOR UPDATE. One gets the lock and reads 1; the other blocks until the first commits.

Java
conn.setAutoCommit(false);int stock;try (PreparedStatement ps = conn.prepareStatement(        "SELECT stock FROM products WHERE product_id = ? FOR UPDATE")) {    ps.setInt(1, productId);    try (ResultSet rs = ps.executeQuery()) {        rs.next();        stock = rs.getInt("stock");   // locked until commit or rollback    }}
Two buyers want the last unit of a product. Buyer A runs SELECT ... FOR UPDATE and gets the row lock, reads stock 1, updates it to 0 and commits. Buyer B runs the same SELECT but must wait until A commits. When B gets the row it reads stock 0 and refuses the order, so nothing is oversold.

Example 2 · The fix: SELECT ... FOR UPDATE

Runs in: a Maven project with the MySQL driver and the ShopLite database

ForUpdateDemo.javaJava
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.List;import java.util.concurrent.CopyOnWriteArrayList;import java.util.concurrent.CyclicBarrier;
public class ForUpdateDemo {    static final int IPHONE = 3;    static final List<Integer> demoOrders = new CopyOnWriteArrayList<>();
    static Connection connect() throws SQLException {        return DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));    }
    static int readStock(Connection conn) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement("SELECT stock FROM products WHERE product_id = ?")) {            ps.setInt(1, IPHONE);            try (ResultSet rs = ps.executeQuery()) {                rs.next();                return rs.getInt("stock");            }        }    }
    static void writeStock(Connection conn, int value) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement("UPDATE products SET stock = ? WHERE product_id = ?")) {            ps.setInt(1, value);            ps.setInt(2, IPHONE);            ps.executeUpdate();        }    }
    static void saveOrder(Connection conn, int customerId, int addressId) throws SQLException {        int orderId;        try (PreparedStatement ps = conn.prepareStatement(                "INSERT INTO orders (customer_id, address_id) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS)) {            ps.setInt(1, customerId);            ps.setInt(2, addressId);            ps.executeUpdate();            try (ResultSet keys = ps.getGeneratedKeys()) {                keys.next();                orderId = keys.getInt(1);            }        }        try (PreparedStatement ps = conn.prepareStatement(                "INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (?, ?, 1, ?)")) {            ps.setInt(1, orderId);            ps.setInt(2, IPHONE);            ps.setBigDecimal(3, new BigDecimal("69900.00"));            ps.executeUpdate();        }        demoOrders.add(orderId);    }
    static void waitForOther(CyclicBarrier barrier) {        try {            barrier.await();        } catch (Exception e) {            throw new IllegalStateException(e);        }    }
    // FIX: lock the row while reading it; the lock is held until commit or rollback    static int lockStock(Connection conn) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement(                "SELECT stock FROM products WHERE product_id = ? FOR UPDATE")) {            ps.setInt(1, IPHONE);            try (ResultSet rs = ps.executeQuery()) {                rs.next();                return rs.getInt("stock");            }        }    }
    static String buy(int customerId, int addressId, CyclicBarrier startTogether) {        try (Connection conn = connect()) {            conn.setAutoCommit(false);            try {                waitForOther(startTogether);         // both buyers press "Pay" at the same moment                int stock = lockStock(conn);         // the second buyer waits here                if (stock < 1) {                    conn.rollback();                    return "out of stock (saw stock " + stock + ")";                }                writeStock(conn, stock - 1);                saveOrder(conn, customerId, addressId);                conn.commit();                return "order placed (saw stock " + stock + ")";            } catch (SQLException | RuntimeException e) {                conn.rollback();                return "failed, " + e.getMessage();            }        } catch (SQLException e) {            return "no connection, " + e.getMessage();        }    }
    public static void main(String[] args) throws Exception {        try (Connection conn = connect()) {            writeStock(conn, 1);        }
        CyclicBarrier startTogether = new CyclicBarrier(2);        List<String> results = new CopyOnWriteArrayList<>();        Thread asha = new Thread(() -> results.add(buy(1, 1, startTogether)));        Thread ravi = new Thread(() -> results.add(buy(2, 3, startTogether)));        asha.start();        ravi.start();        asha.join();        ravi.join();
        results.stream().sorted().forEach(r -> System.out.println("One buyer: " + r));        try (Connection conn = connect()) {            System.out.println("Orders for the last iPhone: " + demoOrders.size()                    + ", stock now: " + readStock(conn));
            try (PreparedStatement ps = conn.prepareStatement("DELETE FROM orders WHERE order_id = ?")) {                for (int orderId : demoOrders) {                    ps.setInt(1, orderId);                    ps.executeUpdate();                }            }            writeStock(conn, 8);        }    }}
Sample output
One buyer: order placed (saw stock 1)
One buyer: out of stock (saw stock 0)
Orders for the last iPhone: 1, stock now: 0

What this code does

  • The barrier now sits before the read, so both buyers ask for the lock at the same moment. The second one blocks inside its SELECT ... FOR UPDATE until the first commits.
  • The waiting buyer then reads 0 and refuses. Which person wins changes from run to run, so the program prints the results without names: always one order placed, one out of stock.

The lock stays until the transaction commits or rolls back, and the second buyer then reads the latest committed value, 0, so it refuses the order. Use it only with auto-commit off: with auto-commit on, the lock is released the moment the SELECT finishes. Keep the time between the locking read and commit() short, and never wait for user input while holding a lock.

Fix the error

Make the read lock the row

Each version still lets two buyers through. Pick the replacement for the highlighted line.

Round 1 of 2

The read must lock the row.

conn.setAutoCommit(false);
try (PreparedStatement ps = conn.prepareStatement(
"SELECT stock FROM products WHERE product_id = ?")) {
ps.setInt(1, productId);
ResultSet rs = ps.executeQuery();
}

Error

No error, but both buyers read 1 and both get an order.

The single conditional UPDATE, and when each fits

The conditional UPDATE from the order lesson is also safe under concurrency, because the UPDATE locks the row itself. Example 3 gives the same result as Example 2 with one statement.

Example 3 · The other fix: one conditional UPDATE

Runs in: a Maven project with the MySQL driver and the ShopLite database

ConditionalUpdateDemo.javaJava
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.List;import java.util.concurrent.CopyOnWriteArrayList;import java.util.concurrent.CyclicBarrier;
public class ConditionalUpdateDemo {    static final int IPHONE = 3;    static final List<Integer> demoOrders = new CopyOnWriteArrayList<>();
    static Connection connect() throws SQLException {        return DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));    }
    static int readStock(Connection conn) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement("SELECT stock FROM products WHERE product_id = ?")) {            ps.setInt(1, IPHONE);            try (ResultSet rs = ps.executeQuery()) {                rs.next();                return rs.getInt("stock");            }        }    }
    static void writeStock(Connection conn, int value) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement("UPDATE products SET stock = ? WHERE product_id = ?")) {            ps.setInt(1, value);            ps.setInt(2, IPHONE);            ps.executeUpdate();        }    }
    static void saveOrder(Connection conn, int customerId, int addressId) throws SQLException {        int orderId;        try (PreparedStatement ps = conn.prepareStatement(                "INSERT INTO orders (customer_id, address_id) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS)) {            ps.setInt(1, customerId);            ps.setInt(2, addressId);            ps.executeUpdate();            try (ResultSet keys = ps.getGeneratedKeys()) {                keys.next();                orderId = keys.getInt(1);            }        }        try (PreparedStatement ps = conn.prepareStatement(                "INSERT INTO order_items (order_id, product_id, quantity, unit_price) VALUES (?, ?, 1, ?)")) {            ps.setInt(1, orderId);            ps.setInt(2, IPHONE);            ps.setBigDecimal(3, new BigDecimal("69900.00"));            ps.executeUpdate();        }        demoOrders.add(orderId);    }
    static void waitForOther(CyclicBarrier barrier) {        try {            barrier.await();        } catch (Exception e) {            throw new IllegalStateException(e);        }    }
    // FIX: check and change the stock in ONE statement; the database does the arithmetic    static boolean takeOne(Connection conn) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement(                "UPDATE products SET stock = stock - 1 WHERE product_id = ? AND stock >= 1")) {            ps.setInt(1, IPHONE);            return ps.executeUpdate() == 1;        }    }
    static String buy(int customerId, int addressId, CyclicBarrier startTogether) {        try (Connection conn = connect()) {            conn.setAutoCommit(false);            try {                waitForOther(startTogether);                if (!takeOne(conn)) {                // the second buyer waits, then changes 0 rows                    conn.rollback();                    return "out of stock";                }                saveOrder(conn, customerId, addressId);                conn.commit();                return "order placed";            } catch (SQLException | RuntimeException e) {                conn.rollback();                return "failed, " + e.getMessage();            }        } catch (SQLException e) {            return "no connection, " + e.getMessage();        }    }
    public static void main(String[] args) throws Exception {        try (Connection conn = connect()) {            writeStock(conn, 1);                     // the last iPhone        }
        CyclicBarrier startTogether = new CyclicBarrier(2);        List<String> results = new CopyOnWriteArrayList<>();        Thread asha = new Thread(() -> results.add(buy(1, 1, startTogether)));        Thread ravi = new Thread(() -> results.add(buy(2, 3, startTogether)));        asha.start();        ravi.start();        asha.join();        ravi.join();
        results.stream().sorted().forEach(r -> System.out.println("One buyer: " + r));        try (Connection conn = connect()) {            System.out.println("Orders for the last iPhone: " + demoOrders.size()                    + ", stock now: " + readStock(conn));
            try (PreparedStatement ps = conn.prepareStatement("DELETE FROM orders WHERE order_id = ?")) {                for (int orderId : demoOrders) {                    ps.setInt(1, orderId);                    ps.executeUpdate();                }            }            writeStock(conn, 8);        }    }}
Sample output
One buyer: order placed
One buyer: out of stock
Orders for the last iPhone: 1, stock now: 0

What this code does

  • takeOne both checks and changes the stock. The second UPDATE waits for the first transaction's row lock, then sees stock 0, so stock >= 1 is false and 0 rows change.
  • No Java-side read is needed at all, so there is nothing stale to write back. The result matches Example 2.

UPDATE products SET stock = stock - 1 WHERE product_id = ? AND stock >= 1: the second buyer's UPDATE waits, then checks stock >= 1 against the new value and changes 0 rows. When each fits:

  • Conditional UPDATE: the rule is a simple condition on the row being changed. One round trip, and the lock is held for the shortest time.
  • FOR UPDATE: you need the values in Java before deciding, such as the name and price for the order line, several rows checked together, or a rule that SQL cannot express easily.

Deadlocks (1213) and lock wait timeouts (1205)

A deadlock happens when two transactions each hold a lock the other one needs, so neither can continue. InnoDB rolls one of them back, the victim, with error 1213.

Locks can collide in two ways. Example 4 waits too long for a lock (error 1205, after 2 seconds). Example 5 builds a deadlock between two buyers.

Example 4 · A lock wait timeout: error 1205

Runs in: a Maven project with the MySQL driver and the ShopLite database

LockTimeoutDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class LockTimeoutDemo {    static Connection connect() throws SQLException {        return DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));    }
    static int lockStock(Connection conn, int productId) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement(                "SELECT stock FROM products WHERE product_id = ? FOR UPDATE")) {            ps.setInt(1, productId);            try (ResultSet rs = ps.executeQuery()) {                rs.next();                return rs.getInt("stock");            }        }    }
    public static void main(String[] args) throws SQLException {        try (Connection a = connect(); Connection b = connect()) {            a.setAutoCommit(false);            b.setAutoCommit(false);            try (Statement st = b.createStatement()) {                st.execute("SET SESSION innodb_lock_wait_timeout = 2");   // seconds; the default is 50            }
            System.out.println("A locks the iPhone row, stock " + lockStock(a, 3));            try {                lockStock(b, 3);                  // waits for A's lock, then gives up            } catch (SQLException e) {                System.out.println("B waited 2 seconds and gave up");                System.out.println("  error code: " + e.getErrorCode());                System.out.println("  SQLState:   " + e.getSQLState());                System.out.println("  message:    " + e.getMessage());                System.out.println("  class:      " + e.getClass().getSimpleName());                b.rollback();            }            a.commit();            System.out.println("A committed; B can now lock it: stock " + lockStock(b, 3));            b.commit();        }    }}
Output
A locks the iPhone row, stock 8
B waited 2 seconds and gave up
  error code: 1205
  SQLState:   40001
  message:    Lock wait timeout exceeded; try restarting transaction
  class:      MySQLTransactionRollbackException
A committed; B can now lock it: stock 8

What this code does

  • A holds the iPhone row lock. B, with innodb_lock_wait_timeout = 2, waits 2 seconds in its FOR UPDATE and gets error 1205, SQLState 40001, as a MySQLTransactionRollbackException.
  • B calls rollback() itself, because MySQL only undid the waiting statement. After A commits, B can take the lock immediately.

Example 5 · A deadlock: error 1213

Runs in: a Maven project with the MySQL driver and the ShopLite database

DeadlockDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.SQLTransactionRollbackException;import java.util.List;import java.util.concurrent.CopyOnWriteArrayList;import java.util.concurrent.CyclicBarrier;
public class DeadlockDemo {    static Connection connect() throws SQLException {        return DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));    }
    static void lock(Connection conn, int productId) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement(                "SELECT stock FROM products WHERE product_id = ? FOR UPDATE")) {            ps.setInt(1, productId);            try (ResultSet rs = ps.executeQuery()) {                rs.next();            }        }    }
    // Locks 'first', waits until the other buyer holds its first row, then locks 'second'    static String buy(int first, int second, CyclicBarrier bothHoldOne) {        try (Connection conn = connect()) {            conn.setAutoCommit(false);            try {                lock(conn, first);                bothHoldOne.await();                lock(conn, second);                conn.commit();                return "committed";            } catch (SQLTransactionRollbackException e) {   // the deadlock victim lands here                conn.rollback();                return "error " + e.getErrorCode() + ", SQLState " + e.getSQLState() + "\n  " + e.getMessage();            }        } catch (Exception e) {            return "unexpected: " + e;        }    }
    public static void main(String[] args) throws InterruptedException {        CyclicBarrier bothHoldOne = new CyclicBarrier(2);        List<String> results = new CopyOnWriteArrayList<>();        Thread asha = new Thread(() -> results.add(buy(1, 2, bothHoldOne)));   // Redmi, then Galaxy        Thread ravi = new Thread(() -> results.add(buy(2, 1, bothHoldOne)));        asha.start();        ravi.start();        asha.join();        ravi.join();
        results.stream().sorted().forEach(r -> System.out.println("One buyer: " + r));    }}
Sample output
One buyer: committed
One buyer: error 1213, SQLState 40001
  Deadlock found when trying to get lock; try restarting transaction

What this code does

  • Asha locks Redmi then wants Galaxy; Ravi locks Galaxy then wants Redmi. The barrier makes both hold their first lock before asking for the second, so the cycle happens every run.
  • InnoDB picks one victim and rolls it back with 1213; the other transaction then gets its lock and commits. Catching SQLTransactionRollbackException catches it without looking at codes.

A lock wait timeout happens when a transaction waits for a lock longer than innodb_lock_wait_timeout (50 seconds by default). MySQL gives up with error 1205, "Lock wait timeout exceeded". By default only the waiting statement is undone; your transaction is still open, so roll it back yourself.

In the deadlock, Asha locks the Redmi and wants the Galaxy while Ravi locks the Galaxy and wants the Redmi, and InnoDB detects the cycle at once. MySQL Connector/J reports both errors with SQLState 40001 and throws MySQLTransactionRollbackException, a subclass of SQLTransactionRollbackException. Both mean "try the whole transaction again".

Predict the output

Which error does MySQL report?

Default settings. Name what each program sees.

Round 1 of 2

B waits for a row that A locked and never commits.

a.setAutoCommit(false);
lockStock(a, 3); // A holds the lock and stays idle
b.setAutoCommit(false);
lockStock(b, 3); // B waits for 50 seconds

Locking rows in a fixed order, and retrying

Lock order is a fixed rule for the order in which every transaction locks rows, for example by ascending product_id. With one shared order, two transactions cannot wait for each other in a circle.

Example 6 sorts the cart by product_id before locking, and wraps the whole transaction in a retry for the rare collision that is left.

Example 6 · Fixed lock order plus a retry

Runs in: a Maven project with the MySQL driver and the ShopLite database

FixedOrderRetryDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.List;import java.util.Map;import java.util.TreeMap;import java.util.concurrent.CopyOnWriteArrayList;
@FunctionalInterfaceinterface SqlWork {    void run(Connection conn) throws SQLException;}
public class FixedOrderRetryDemo {    static Connection connect() throws SQLException {        return DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));    }
    static boolean isRetryable(SQLException e) {        return e.getErrorCode() == 1213 || e.getErrorCode() == 1205 || "40001".equals(e.getSQLState());    }
    // Runs the work in a new transaction; on a deadlock or lock timeout, rolls back and tries again    static int inTransactionWithRetry(int maxAttempts, SqlWork work) throws SQLException, InterruptedException {        for (int attempt = 1; ; attempt++) {            try (Connection conn = connect()) {                conn.setAutoCommit(false);                try {                    work.run(conn);                    conn.commit();                    return attempt;                } catch (SQLException e) {                    conn.rollback();                    if (!isRetryable(e) || attempt == maxAttempts) {                        throw e;                    }                } catch (RuntimeException e) {                    conn.rollback();                 // business errors are never retried                    throw e;                }            }            Thread.sleep(50L * attempt);   // a short pause before the next try        }    }
    static void buyCart(Connection conn, Map<Integer, Integer> cart) throws SQLException {        Map<Integer, Integer> sorted = new TreeMap<>(cart);        try (PreparedStatement lock = conn.prepareStatement(                "SELECT stock FROM products WHERE product_id = ? FOR UPDATE")) {            for (int productId : sorted.keySet()) {                lock.setInt(1, productId);                try (ResultSet rs = lock.executeQuery()) {                    rs.next();                }            }        }        try (PreparedStatement take = conn.prepareStatement(                "UPDATE products SET stock = stock - ? WHERE product_id = ? AND stock >= ?")) {            for (Map.Entry<Integer, Integer> line : sorted.entrySet()) {                take.setInt(1, line.getValue());                take.setInt(2, line.getKey());                take.setInt(3, line.getValue());                if (take.executeUpdate() == 0) {                    throw new IllegalStateException("not enough stock for product " + line.getKey());                }            }        }    }
    static String stockLine() throws SQLException {        try (Connection conn = connect();             PreparedStatement ps = conn.prepareStatement(                     "SELECT stock FROM products WHERE product_id IN (1, 2) ORDER BY product_id");             ResultSet rs = ps.executeQuery()) {            rs.next();            int redmi = rs.getInt(1);            rs.next();            return "Redmi " + redmi + ", Galaxy " + rs.getInt(1);        }    }
    static Thread buyer(String name, Map<Integer, Integer> cart, List<String> results) {        return new Thread(() -> {            try {                int attempts = inTransactionWithRetry(3, conn -> buyCart(conn, cart));                results.add(name + ": done in " + attempts + " attempt(s)");            } catch (Exception e) {                results.add(name + ": failed, " + e.getMessage());            }        });    }
    public static void main(String[] args) throws Exception {        System.out.println("Stock before: " + stockLine());        List<String> results = new CopyOnWriteArrayList<>();        Thread asha = buyer("Asha", Map.of(1, 1, 2, 1), results);        Thread ravi = buyer("Ravi", Map.of(2, 1, 1, 1), results);        asha.start();        ravi.start();        asha.join();        ravi.join();        results.stream().sorted().forEach(System.out::println);        System.out.println("Stock after:  " + stockLine());
        inTransactionWithRetry(1, conn -> {            try (PreparedStatement ps = conn.prepareStatement(                    "UPDATE products SET stock = stock + 2 WHERE product_id IN (1, 2)")) {                ps.executeUpdate();            }        });    }}
Sample output
Stock before: Redmi 40, Galaxy 25
Asha: done in 1 attempt(s)
Ravi: done in 1 attempt(s)
Stock after:  Redmi 38, Galaxy 23

What this code does

  • The carts list the same phones in opposite order, but buyCart locks rows in product_id order (a TreeMap), so neither buyer can hold the row the other needs first. Both finish in 1 attempt.
  • inTransactionWithRetry runs the whole transaction again on 1213, 1205 or SQLState 40001, up to 3 times, and never retries business errors. The program puts the phones back at the end.

Most deadlocks come from two transactions locking the same rows in different orders. With a fixed order, whoever gets the first row first also gets the second, and the other one simply waits.

Deadlocks can still happen in busy systems for other reasons, so add a retry: on error 1213 or 1205 (or SQLState 40001), roll back, wait a moment and run the whole transaction again, up to about 3 attempts. Never retry other errors: a duplicate email will fail every time. The retry repeats the whole transaction from a fresh start, never only the failed statement.

Find the bug

Find the retry bug

Each snippet should retry a deadlocked transaction safely. Tap the wrong line.

Retry only when the database asks for it.

Round 1 of 2

Next step

Check your understanding

11 quick questions