Check-then-act bugs
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A check-then-act bug happens when a thread checks something, then acts on what it saw, but another thread changes the data in between. The check was true when it ran and is false by the time the action happens.
The last train seat booked twice
Check-then-act is a pair of steps: check a condition, such as if (seatsLeft > 0), and then act on it, such as seatsLeft--. With one thread the pair is safe. With two threads, both can pass the check before either one acts.
Example 1 · Check-then-act with one thread: works
class Train { int seatsLeft = 1;
boolean book(String passenger) { if (seatsLeft > 0) { // check seatsLeft--; // act System.out.println(passenger + " got the seat"); return true; } System.out.println(passenger + " is on the waiting list"); return false; }}
public class OneThreadBookingDemo { public static void main(String[] args) { Train train = new Train(); train.book("Asha"); train.book("Ravi"); System.out.println("Seats left: " + train.seatsLeft); }}Asha got the seat Ravi is on the waiting list Seats left: 0
What this code does
- With one thread, Ravi's check runs after Asha's act, so Ravi sees
seatsLeft == 0and goes to the waiting list. - The method looks correct, and with one thread it is. The next example runs the same idea on two threads.
Example 2 · Two threads book the last seat
class Train { int seatsLeft = 1;
boolean book() { if (seatsLeft > 0) { // check pause(50); // slow step: taking the payment seatsLeft--; // act return true; } return false; }
static void pause(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }}
public class DoubleBookingDemo { public static void main(String[] args) throws InterruptedException { Train train = new Train(); boolean[] booked = new boolean[2]; Thread asha = new Thread(() -> booked[0] = train.book(), "Asha"); Thread ravi = new Thread(() -> booked[1] = train.book(), "Ravi"); asha.start(); ravi.start(); asha.join(); ravi.join(); System.out.println("Asha booked: " + booked[0]); System.out.println("Ravi booked: " + booked[1]); System.out.println("Seats left: " + train.seatsLeft); }}Asha booked: true Ravi booked: true Seats left: -1
What this code does
- Both threads pass
seatsLeft > 0while the other is still in its payment step, so both book and the count drops to -1. Two passengers now hold one seat. - The results are printed by
mainafter bothjoin()calls, so the lines always come out in this order. Whether both bookings succeed depends on timing; the 50 ms pause makes it happen on almost every run. Now and thenseatsLefteven ends at 0 with both booked: the twoseatsLeft--steps collided, a lost update on top of the double booking.
Picture the Tatkal rush. One seat is left, and two passengers press "Book" at the same moment. Both requests see one free seat, both take payment, and both get a ticket for the same seat. The programs above put a short Thread.sleep between the check and the act. It stands for slow real work, like taking a payment, and it makes the gap wide enough to see on every run. Without it the gap is tiny, so the bug appears rarely, which makes it even harder to find.
containsKey followed by put on a shared map
containsKey then put is check-then-act on a map: check whether a key is free, then add it. Two threads can both see that the key is free, and both add it.
Example 3 · Two teams register the same name
import java.util.HashMap;import java.util.Map;
class FestRegistry { private final Map<String, String> teams = new HashMap<>();
boolean register(String team, String leader) { if (!teams.containsKey(team)) { // check pause(50); // slow step: checking the leader's college ID teams.put(team, leader); // act return true; } return false; }
int size() { return teams.size(); }
static void pause(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }}
public class TeamNameRaceDemo { public static void main(String[] args) throws InterruptedException { FestRegistry registry = new FestRegistry(); boolean[] ok = new boolean[2]; Thread meera = new Thread(() -> ok[0] = registry.register("CodeStorm", "Meera"), "Meera"); Thread kabir = new Thread(() -> ok[1] = registry.register("CodeStorm", "Kabir"), "Kabir"); meera.start(); kabir.start(); meera.join(); kabir.join(); System.out.println("Meera registered CodeStorm: " + ok[0]); System.out.println("Kabir registered CodeStorm: " + ok[1]); System.out.println("Teams in the map: " + registry.size()); }}Meera registered CodeStorm: true Kabir registered CodeStorm: true Teams in the map: 1
What this code does
- Both threads see that
CodeStormis free, so both are toldtrue. The map (team name to leader) holds only one entry, because the secondputreplaced the first leader without any error. - Which leader is left depends on which
putran last, and that changes from run to run. On rare runs even the count is wrong, becauseHashMapitself can break when two threads callputat once.
The second put silently replaces the first value. Both threads were told they succeeded, but only one entry is left. In a college fest app, two teams could both be told they own the team name "CodeStorm". HashMap is also not safe for many threads in other ways; the Concurrent Collections module covers that. But even a map that is safe for single calls has this bug, because the check and the put are still two separate calls.
Lazy initialisation that creates two objects
Lazy initialisation means creating an object only the first time someone asks for it: if (instance == null) instance = new AppConfig();. It saves work when the object is expensive and may never be needed.
Example 4 · Lazy initialisation creates two config objects
class AppConfig { private static AppConfig instance;
private AppConfig() { System.out.println("Reading config file..."); try { Thread.sleep(50); // reading a file takes time } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
static AppConfig get() { if (instance == null) { // check instance = new AppConfig(); // act } return instance; }}
public class LazyInitRaceDemo { public static void main(String[] args) throws InterruptedException { AppConfig[] got = new AppConfig[2]; Thread t1 = new Thread(() -> got[0] = AppConfig.get(), "request-1"); Thread t2 = new Thread(() -> got[1] = AppConfig.get(), "request-2"); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Same object for both requests? " + (got[0] == got[1])); }}Reading config file... Reading config file... Same object for both requests? false
What this code does
instanceis set only after the constructor finishes. While the first thread is still reading the file, the second thread also seesnulland builds its own object.- Two "Reading config file..." lines mean two objects were built. The last line is usually
false; it can betruewhen one thread replacedinstancebefore the other reachedreturn instance, but the file was still read twice.
It is check-then-act too. Two threads can both see null, and both create an object. The program then has two "only" config objects, may read a file twice and may give different threads different objects. The Visibility module returns to this pattern, called the singleton trap, and shows the safe ways to write it.
Compound actions must be atomic
An action is atomic when other threads can see it only as not started or fully done, never half done. A compound action is a group of steps that must be atomic as a whole: check-then-act, and the read-modify-write of count++.
Example 5 · One booking thread does every check and act
import java.util.ArrayList;import java.util.List;
class Train { int seatsLeft = 2;
String book(String passenger) { if (seatsLeft > 0) { // check seatsLeft--; // act: no other thread can run in between return passenger + ": confirmed"; } return passenger + ": waiting list"; }}
public class SingleOwnerBookingDemo { public static void main(String[] args) throws InterruptedException { Train train = new Train(); String[] requests = {"Asha", "Ravi", "Imran", "Divya"}; List<String> results = new ArrayList<>();
// Only this thread touches the train, so every check-then-act is atomic. Thread bookingDesk = new Thread(() -> { for (String passenger : requests) { results.add(train.book(passenger)); } }, "booking-desk");
bookingDesk.start(); bookingDesk.join(); for (String r : results) { System.out.println(r); } System.out.println("Seats left: " + train.seatsLeft); }}Asha: confirmed Ravi: confirmed Imran: waiting list Divya: waiting list Seats left: 0
What this code does
- All four requests go to one
booking-deskthread. Each check and act onseatsLefthappens with no other thread in between, so the pair behaves atomically and nobody gets a seat twice. mainreadsresultsonly afterjoin(). This single-owner design is simple and correct, but only one booking happens at a time;synchronized, in the next lesson, lets many threads share the train safely.
Making each single step safe is not enough. What must not happen is another thread changing the data between the steps. So the whole group needs protection, from the check to the act. One way that needs no new tools is to let a single thread own the data: other threads hand it requests, and it does every check and act itself. The usual way is to make threads take turns on the whole group, which is what Java's synchronized keyword does, starting in the next lesson.
Find the bug
Find the check-then-act bug
Every method here is synchronized or uses a thread-safe class. Click the line that still has a race.
Book the last seat.
Round 1 of 4Next step
Check your understanding
11 quick questions