Half a transfer committed to the pool
A hard Java puzzle in the sql and jdbc mistakes family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.
Highlighted: line 7. Play this one as a puzzle without the answer.
What is wrong
If the second update throws, the method exits without rollback and without restoring autocommit. The connection returns to the pool with an open transaction and the first update pending; a later user of that connection may commit or lose it.
The fix
How to avoid it next time
Roll back on failure and restore autocommit, or let Spring @Transactional manage it.
Want the background? Read JDBC transactions and batching in the Java concepts library.
About sql and jdbc mistakes
Building SQL by string concatenation invites injection, and a handful of subtle JDBC habits leak connections, load too much data or commit half a change.
In code review: Search for plus signs inside strings passed to executeQuery, createQuery or createNativeQuery. Parameters belong in placeholders, never in the text.
More puzzles in this family
Frequently asked questions
What is the bug in "Half a transfer committed to the pool"?
If the second update throws, the method exits without rollback and without restoring autocommit. The connection returns to the pool with an open transaction and the first update pending; a later user of that connection may commit or lose it. The faulty line is line 7: c.setAutoCommit(false);
How do I fix it?
Replace it with: try { update(c, from, -cents); update(c, to, cents); c.commit(); } catch (SQLException e) { c.rollback(); throw e; }. Roll back on failure and restore autocommit, or let Spring @Transactional manage it.
How do I catch sql and jdbc mistakes in code review?
Search for plus signs inside strings passed to executeQuery, createQuery or createNativeQuery. Parameters belong in placeholders, never in the text.
Is there a new puzzle every day?
Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.