Isolation levels
Isolation levels decide what one transaction can see of another's uncommitted or committed work. JDBC names four: read uncommitted, read committed, repeatable read, and serializable. Higher isolation means fewer anomalies and more waiting.
Detailed Explanation
Without isolation, you get dirty reads (see uncommitted data), non-repeatable reads (a row changes between your two reads), and phantoms (a new row appears in a range you already queried). The SQL standard maps levels to which anomalies are forbidden. Databases implement this with locks or MVCC.
Read uncommitted allows dirty reads. Rare in PostgreSQL (it treats it as read committed). Read committed (Postgres default, Oracle default) sees only committed data; two reads of one row can differ. Repeatable read (MySQL InnoDB default) keeps your snapshot of existing rows; phantoms may still appear depending on the engine. Serializable makes the outcome match some serial order; Postgres uses SSI and may throw a serialization failure you must retry.
JDBC: connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE). Spring: @Transactional(isolation = Isolation.REPEATABLE_READ). The database may silently upgrade a level it does not support.
You reach for a higher level when a read-modify-write must not lose updates (balance = balance - 10 in two tabs). You can also use SELECT ... FOR UPDATE or an optimistic @Version column. You keep the default when lost updates are not the risk.
The cost of serializable is retries under contention. The cost of read committed on a check-then-act is a lost update. The cost of assuming MySQL's repeatable read equals Postgres's is a porting bug.
Document the level next to the money path. Tests should use the same database family as production.
A lost-update story: two requests read balance 100, both subtract 30, both write 70. Read committed allows that. UPDATE accounts SET bal = bal - 30 WHERE id = ? is one statement and avoids the race without raising isolation. When the logic cannot live in one statement, take SELECT ... FOR UPDATE inside a short transaction, or store a version column and fail the second writer. Isolation is one tool. Often the cheaper fix is a single SQL expression or optimistic locking.
Code Examples
import java.sql.Connection;
public class Iso {
static void serializable(Connection c) throws Exception {
c.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
c.setAutoCommit(false);
try {
// work that must not see concurrent writes
c.commit();
} catch (Exception e) {
c.rollback();
throw e;
} finally {
c.setAutoCommit(true);
}
}
}public class Levels {
public static void main(String[] args) {
System.out.println(Connection.TRANSACTION_READ_COMMITTED);
// prints: 2
System.out.println(Connection.TRANSACTION_SERIALIZABLE);
// prints: 8
}
}Common Gotchas
Defaults differ
Postgres read committed vs MySQL repeatable read.
Serializable can throw
retry the whole transaction; do not assume commit always works.