Transactions: All or Nothing

Transactions: All or Nothing in Java: A bank transfer is two operations: subtract from account A, add to account B.

Concept Explanation

A bank transfer is two operations: subtract from account A, add to account B. If the program crashes between them, money vanishes. A transaction groups operations so that either all succeed or none do.

By default JDBC runs in auto-commit mode — every statement commits immediately, which is exactly what you do not want here.


The Pattern

Connection conn = dataSource.getConnection();
try {
    conn.setAutoCommit(false);              // begin transaction

    try (PreparedStatement debit = conn.prepareStatement(
            "UPDATE accounts SET balance = balance - ? WHERE id = ?")) {
        debit.setBigDecimal(1, amount);
        debit.setLong(2, fromId);
        debit.executeUpdate();
    }

    try (PreparedStatement credit = conn.prepareStatement(
            "UPDATE accounts SET balance = balance + ? WHERE id = ?")) {
        credit.setBigDecimal(1, amount);
        credit.setLong(2, toId);
        credit.executeUpdate();
    }

    conn.commit();                          // both succeeded
} catch (SQLException e) {
    conn.rollback();                        // undo everything
    throw e;
} finally {
    conn.setAutoCommit(true);               // restore before returning to pool
    conn.close();
}

ACID, Briefly

  • Atomicity — all or nothing.
  • Consistency — constraints hold before and after.
  • Isolation — concurrent transactions do not see each other's half-finished work.
  • Durability — once committed, a crash cannot lose it.

Isolation Levels

LevelPrevents
READ_UNCOMMITTEDnothing (can read uncommitted "dirty" data)
READ_COMMITTEDdirty reads — the common default
REPEATABLE_READdirty + non-repeatable reads
SERIALIZABLEeverything, at the cost of concurrency
conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

Savepoints

For partial rollback inside a long transaction:

Savepoint sp = conn.setSavepoint("afterDebit");
// ... more work ...
conn.rollback(sp);      // undo back to the savepoint only

Common Mistakes

  1. Forgetting setAutoCommit(false): Each statement commits on its own and rollback() does nothing.
  2. No rollback in catch: The transaction stays open, holding locks until it times out.
  3. Leaving auto-commit off on a pooled connection: The next borrower inherits your broken state. Always restore it.
  4. Transactions that span user input: Never hold a transaction open while waiting for a human.

Best Practices

  • Keep them short: Long transactions hold locks and block other work.
  • Use the weakest sufficient isolation: SERIALIZABLE everywhere will throttle your app.
  • In Spring, prefer @Transactional over manual commit/rollback — far less to get wrong.

Practice Exercises

  1. The Transfer: Implement the bank transfer above, then throw a deliberate exception between the two updates and confirm no money moved.
  2. The Savepoint: Insert three rows inside one transaction, set a savepoint after the second, then roll back to it and verify only two remain.
  3. The Dirty Read: With two connections, set one to READ_UNCOMMITTED and observe it reading the other's uncommitted change.