Skip to lesson

Setting the isolation level

While one customer pays for the last pair of shoes, another customer reads the stock. Should the second one see the unpaid change or not? JDBC lets each connection choose.

Recap: dirty reads, non-repeatable reads and phantoms

An isolation level is a setting that decides how much one transaction sees of other transactions running at the same time. Stronger levels remove more problems but make transactions wait more.

Overlapping transactions can cause three problems, as the SQL section's Isolation lessons showed:

  • A dirty read: you read a change another transaction has not committed yet, and it may still be rolled back.
  • A non-repeatable read: you read the same row twice and get two values, because someone committed in between.
  • A phantom read: you run the same search twice and a new matching row appears.

Each level below removes more of these. The list follows the SQL standard; the next sections show MySQL's real behaviour from Java.

  • READ UNCOMMITTED: dirty, non-repeatable and phantom reads are all possible.
  • READ COMMITTED: no dirty reads; non-repeatable and phantom reads are possible.
  • REPEATABLE READ: no dirty or non-repeatable reads; the standard allows phantoms, InnoDB prevents them for plain reads.
  • SERIALIZABLE: none of the three.

setTransactionIsolation and the Connection.TRANSACTION_* constants

conn.setTransactionIsolation(level) sets the level for the transactions this connection runs next. Example 1 reads the level, changes it and checks the change.

Example 1 · Reading and setting the level from Java

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

IsolationInfoDemo.javaJava
import java.sql.Connection;import java.sql.DatabaseMetaData;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;
public class IsolationInfoDemo {    static Connection connect() throws SQLException {        return DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));    }
    static String name(int level) {        return switch (level) {            case Connection.TRANSACTION_READ_UNCOMMITTED -> "READ UNCOMMITTED";            case Connection.TRANSACTION_READ_COMMITTED -> "READ COMMITTED";            case Connection.TRANSACTION_REPEATABLE_READ -> "REPEATABLE READ";            case Connection.TRANSACTION_SERIALIZABLE -> "SERIALIZABLE";            default -> "NONE";        };    }
    static String serverLevel(Connection conn) throws SQLException {        try (Statement st = conn.createStatement();             ResultSet rs = st.executeQuery("SELECT @@transaction_isolation")) {            rs.next();            return rs.getString(1);        }    }
    public static void main(String[] args) throws SQLException {        try (Connection conn = connect()) {            DatabaseMetaData meta = conn.getMetaData();            System.out.println("Database default: " + name(meta.getDefaultTransactionIsolation()));            System.out.println("This connection:  " + name(conn.getTransactionIsolation()));
            int[] levels = {                Connection.TRANSACTION_READ_UNCOMMITTED, Connection.TRANSACTION_READ_COMMITTED,                Connection.TRANSACTION_REPEATABLE_READ, Connection.TRANSACTION_SERIALIZABLE            };            for (int level : levels) {                System.out.println("  constant " + level + " = " + name(level)                        + ", supported: " + meta.supportsTransactionIsolationLevel(level));            }
            conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);            System.out.println("After the change: " + name(conn.getTransactionIsolation()));            System.out.println("MySQL session says: " + serverLevel(conn));        }    }}
Output
Database default: REPEATABLE READ
This connection:  REPEATABLE READ
  constant 1 = READ UNCOMMITTED, supported: true
  constant 2 = READ COMMITTED, supported: true
  constant 4 = REPEATABLE READ, supported: true
  constant 8 = SERIALIZABLE, supported: true
After the change: READ COMMITTED
MySQL session says: READ-COMMITTED

What this code does

  • MySQL reports REPEATABLE READ as its default, and supportsTransactionIsolationLevel is true for all four constants (1, 2, 4, 8).
  • After setTransactionIsolation(TRANSACTION_READ_COMMITTED) both the JDBC getter and MySQL's @@transaction_isolation show the new level for this session.

The four constants are int values: TRANSACTION_READ_UNCOMMITTED (1), TRANSACTION_READ_COMMITTED (2), TRANSACTION_REPEATABLE_READ (4) and TRANSACTION_SERIALIZABLE (8). conn.getTransactionIsolation() reads the level back, and DatabaseMetaData tells you what the database supports with getDefaultTransactionIsolation() and supportsTransactionIsolationLevel(level).

Set the level before the transaction starts. MySQL Connector/J changes the session setting, and MySQL applies a session change to the next transaction, not to one that is already running.

Fix the error

Fix the isolation call

Each line should switch the connection to READ COMMITTED. Pick the line that compiles.

Round 1 of 2

Set the level before the transaction starts.

try (Connection conn = connect()) {
conn.setIsolation(Connection.TRANSACTION_READ_COMMITTED);
conn.setAutoCommit(false);
}

Error

error: cannot find symbol
  symbol:   method setIsolation(int)
  location: variable conn of type Connection

MySQL InnoDB's default: REPEATABLE READ

A snapshot is the frozen view of committed data that a REPEATABLE READ transaction reads from, taken at its first read. Every later plain SELECT in that transaction sees the same snapshot.

MySQL's InnoDB engine uses REPEATABLE READ by default. In Example 2 transaction A reads the stock twice while B has already sold 5, then reads it once more with FOR UPDATE.

Example 2 · REPEATABLE READ: a snapshot for plain reads

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

RepeatableReadDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;
public class RepeatableReadDemo {    static Connection connect() throws SQLException {        return DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));    }
    static int stock(Connection conn, String suffix) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement(                "SELECT stock FROM products WHERE product_id = 6" + suffix);             ResultSet rs = ps.executeQuery()) {            rs.next();            return rs.getInt("stock");        }    }
    static void changeStock(Connection conn, int change) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement(                "UPDATE products SET stock = stock + ? WHERE product_id = 6")) {            ps.setInt(1, change);            ps.executeUpdate();        }    }
    public static void main(String[] args) throws SQLException {        try (Connection a = connect(); Connection b = connect()) {            a.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);   // the default anyway            a.setAutoCommit(false);
            System.out.println("A reads:                " + stock(a, ""));   // snapshot starts here            changeStock(b, -5);                                                 // B sells 5, auto-commit            System.out.println("B sold 5 and committed");            System.out.println("A reads again:          " + stock(a, ""));            System.out.println("A reads FOR UPDATE:     " + stock(a, " FOR UPDATE"));            a.commit();            System.out.println("A, in a new transaction: " + stock(a, ""));
            changeStock(b, +5);            a.setAutoCommit(true);        }    }}
Output
A reads:                120
B sold 5 and committed
A reads again:          120
A reads FOR UPDATE:     115
A, in a new transaction: 115

What this code does

  • A's first SELECT fixes its snapshot at 120. B's committed sale does not change A's second plain read.
  • SELECT ... FOR UPDATE reads the latest committed row (115) even inside the same transaction. After commit(), A's next plain read starts a new snapshot and also sees 115.

Every later plain SELECT sees that same snapshot, so values do not change under you and new rows do not appear. One exception matters a lot: a locking read (SELECT ... FOR UPDATE) and every UPDATE work on the latest committed row, which is why the FOR UPDATE read in Example 2 returns 115. So REPEATABLE READ gives a consistent picture for reports, but it does not stop two transactions from changing the same row based on old values.

Predict the output

What does A read?

REPEATABLE READ, stock starts at 120. B sells 5 and commits between the two reads.

Round 1 of 2

A reads the stock with a plain SELECT twice.

a.setAutoCommit(false);
int first = stock(a);
changeStock(b, -5); // B commits
int second = stock(a);
System.out.println(second);
Other databases differ: PostgreSQL, Oracle and SQL Server default to READ COMMITTED.

Two connections side by side

Example 3 runs the same steps at each level. Reader A uses the level under test and reads the Airdopes stock three times: at the start, while B has sold 5 but not committed, and after B commits.

Example 3 · All four levels, one step at a time

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

CompareLevelsDemo.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 CompareLevelsDemo {    static Connection connect() throws SQLException {        return DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"));    }
    static int stock(Connection conn) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement("SELECT stock FROM products WHERE product_id = 6");             ResultSet rs = ps.executeQuery()) {            rs.next();            return rs.getInt("stock");        }    }
    static void changeStock(Connection conn, int change) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement(                "UPDATE products SET stock = stock + ? WHERE product_id = 6")) {            ps.setInt(1, change);            ps.executeUpdate();        }    }
    static void round(String name, int level) throws SQLException {        try (Connection reader = connect(); Connection writer = connect()) {            reader.setTransactionIsolation(level);            reader.setAutoCommit(false);            writer.setAutoCommit(false);            try (Statement st = writer.createStatement()) {                st.execute("SET SESSION innodb_lock_wait_timeout = 1");   // fail fast instead of waiting 50 s            }
            int first = stock(reader);            String during;            boolean sold = false;            try {                changeStock(writer, -5);                // B sells 5, not committed yet                sold = true;                during = String.valueOf(stock(reader));            } catch (SQLException e) {                during = "B blocked, error " + e.getErrorCode();            }            writer.commit();            int afterCommit = stock(reader);            reader.commit();
            System.out.printf("%-17s %5d   %-22s %5d%n", name, first, during, afterCommit);
            if (sold) {                changeStock(writer, +5);                // put the stock back                writer.commit();            }        }    }
    public static void main(String[] args) throws SQLException {        System.out.printf("%-17s %5s   %-22s %s%n", "A's level", "first", "B sold, not committed", "B committed");        round("READ UNCOMMITTED", Connection.TRANSACTION_READ_UNCOMMITTED);        round("READ COMMITTED", Connection.TRANSACTION_READ_COMMITTED);        round("REPEATABLE READ", Connection.TRANSACTION_REPEATABLE_READ);        round("SERIALIZABLE", Connection.TRANSACTION_SERIALIZABLE);    }}
Output
A's level         first   B sold, not committed  B committed
READ UNCOMMITTED    120   115                      115
READ COMMITTED      120   120                      115
REPEATABLE READ     120   120                      120
SERIALIZABLE        120   B blocked, error 1205    120

What this code does

  • Each round opens a reader at one level and a writer B. The middle column is what A sees while B's sale is not committed; READ UNCOMMITTED is the only level that sees 115 there.
  • At SERIALIZABLE, A's read holds a shared lock, so B's UPDATE waits; with innodb_lock_wait_timeout = 1 it fails with 1205. B's sale never happens, so A reads 120 at the end.

What A sees at each level:

  • READ UNCOMMITTED sees 115 before B commits: a dirty read.
  • READ COMMITTED sees the new value only after the commit: a non-repeatable read.
  • REPEATABLE READ sees 120 all through its transaction.
  • SERIALIZABLE turns A's plain reads into shared locks, so B cannot even change the row: B waits and here gives up after 1 second with error 1205.

One program can run both connections, one step after another, because only the SERIALIZABLE step has to wait, and the short lock wait timeout ends that wait.

Why most apps keep the default and lock specific rows

A lost update happens when two transactions write values computed from the same old read, so one change vanishes without any error.

A higher level is not a cure for everything. Example 4 runs two sales at the default level: both read 18 pairs of shoes, and both write 17.

Example 4 · A lost update at the default level

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

LostUpdateDemo.javaJava
import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;
public class LostUpdateDemo {    static final int SHOES = 13;   // Running Shoes, 18 in stock
    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, SHOES);            try (ResultSet rs = ps.executeQuery()) {                rs.next();                return rs.getInt("stock");            }        }    }
    static void writeStock(Connection conn, int newStock) throws SQLException {        try (PreparedStatement ps = conn.prepareStatement("UPDATE products SET stock = ? WHERE product_id = ?")) {            ps.setInt(1, newStock);            ps.setInt(2, SHOES);            ps.executeUpdate();        }    }
    public static void main(String[] args) throws SQLException {        try (Connection a = connect(); Connection b = connect()) {            a.setAutoCommit(false);   // both use the default, REPEATABLE READ            b.setAutoCommit(false);
            int seenByA = readStock(a);            int seenByB = readStock(b);            System.out.println("A reads " + seenByA + ", B reads " + seenByB);
            writeStock(a, seenByA - 1);            a.commit();            System.out.println("A sells 1 pair, writes " + (seenByA - 1) + " and commits");
            writeStock(b, seenByB - 1);            b.commit();            System.out.println("B sells 1 pair, writes " + (seenByB - 1) + " and commits");
            System.out.println("Final stock: " + readStock(a) + " (2 pairs sold, only 1 subtracted)");
            writeStock(a, 18);   // put the stock back for the next run            a.commit();        }    }}
Output
A reads 18, B reads 18
A sells 1 pair, writes 17 and commits
B sells 1 pair, writes 17 and commits
Final stock: 17 (2 pairs sold, only 1 subtracted)

What this code does

  • Both connections read 18 and compute 17 in Java. A commits 17; B then writes 17 too, overwriting A's change without any error.
  • REPEATABLE READ did not stop it, because the bug is "read, decide in Java, write an absolute value". The program puts the stock back to 18 at the end.

Two pairs were sold, one subtraction is lost, and no error appears. SERIALIZABLE would block or fail one of them, but it does that for every read in every transaction, so the whole app waits more and sees more deadlocks. Most applications keep the default level and protect only the rows that matter: a conditional UPDATE (stock = stock - ?) or a locking read with SELECT ... FOR UPDATE. The next lesson does that for the last item in stock.

READ COMMITTED is a common second choice for busy systems that want less locking; choose it on purpose and test it.

Find the bug

Find the lost-update bug

Each snippet can lose a sale or ignore a level. Tap the wrong line.

Sell one pair of shoes safely.

Round 1 of 2

Next step

Check your understanding

11 quick questions