Skip to lesson

Check-then-act bugs

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.

Two threads book the last seat. Seats left is 1. Thread A checks seats greater than 0 and sees yes, thread B checks and also sees yes. A books and seats becomes 0, then B books and seats becomes minus 1. Two passengers got one seat.

Example 1 · Check-then-act with one thread: works

OneThreadBookingDemo.javaJava
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);    }}
Output
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 == 0 and 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

DoubleBookingDemo.javaJava
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);    }}
Sample output
Asha booked: true
Ravi booked: true
Seats left: -1

What this code does

  • Both threads pass seatsLeft > 0 while 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 main after both join() 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 then seatsLeft even ends at 0 with both booked: the two seatsLeft-- 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

TeamNameRaceDemo.javaJava
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());    }}
Sample output
Meera registered CodeStorm: true
Kabir registered CodeStorm: true
Teams in the map: 1

What this code does

  • Both threads see that CodeStorm is free, so both are told true. The map (team name to leader) holds only one entry, because the second put replaced the first leader without any error.
  • Which leader is left depends on which put ran last, and that changes from run to run. On rare runs even the count is wrong, because HashMap itself can break when two threads call put at 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

LazyInitRaceDemo.javaJava
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]));    }}
Sample output
Reading config file...
Reading config file...
Same object for both requests? false

What this code does

  • instance is set only after the constructor finishes. While the first thread is still reading the file, the second thread also sees null and builds its own object.
  • Two "Reading config file..." lines mean two objects were built. The last line is usually false; it can be true when one thread replaced instance before the other reached return 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

SingleOwnerBookingDemo.javaJava
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);    }}
Output
Asha: confirmed
Ravi: confirmed
Imran: waiting list
Divya: waiting list
Seats left: 0

What this code does

  • All four requests go to one booking-desk thread. Each check and act on seatsLeft happens with no other thread in between, so the pair behaves atomically and nobody gets a seat twice.
  • main reads results only after join(). 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 4

Next step

Check your understanding

11 quick questions