Skip to lesson

Visibility: common mistakes and practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Most visibility bugs come from three habits: a plain field used as a flag, volatile trusted to protect a counter, and a lazy object created with a bare null check. Each has a short, reliable fix, and choosing the right tool for each field prevents all three.

Mistake 1: a flag without volatile

A plain flag shared between threads has no happens-before link between the write and the read. The reader may loop forever on most JVMs, or work fine on your laptop and hang on the server.

Example 1 · Mistake: plain flag versus volatile flag

FlagMistakeDemo.javaJava
public class FlagMistakeDemo {    static boolean plainStop = false;             // wrong    static volatile boolean volatileStop = false; // fixed
    public static void main(String[] args) throws InterruptedException {        Thread wrong = new Thread(() -> {            long n = 0;            while (!plainStop) {                n++;            }        }, "exam-timer-wrong");        Thread fixed = new Thread(() -> {            long n = 0;            while (!volatileStop) {                n++;            }        }, "exam-timer-fixed");        wrong.setDaemon(true);                    // so the demo can end either way        fixed.setDaemon(true);        wrong.start();        fixed.start();
        Thread.sleep(100);        plainStop = true;        volatileStop = true;        wrong.join(500);        fixed.join(500);
        System.out.println("Wrong: still running? " + wrong.isAlive());        System.out.println("Fixed: still running? " + fixed.isAlive());    }}
Sample output
Wrong: still running? true
Fixed: still running? false

What this code does

  • Both timers loop until their flag is true, and main sets both. On most HotSpot JVMs the plain-flag timer never notices and is still running after the timeout; the rules allow either result for it.
  • The volatile timer always stops. Both threads are daemons and joined with a timeout only so the demo can end.

The fix is volatile on the flag, or reading and writing it through synchronized methods on the same object. Never fix it with a sleep or a println in the loop: that only hides it.

Mistake 2: volatile where a lock is needed

volatile on a counter or balance looks safe but is not. balance += amount, count++ and if (seats > 0) seats-- all read the old value before writing a new one, and another thread can slip in between.

Example 2 · Mistake: a volatile wallet balance

VolatileWalletDemo.javaJava
class VolatileWallet {    volatile int balance = 0;
    void add(int amount) {        balance += amount;                        // read, add, write: still a race    }}
class LockedWallet {    private int balance = 0;
    synchronized void add(int amount) {        balance += amount;    }
    synchronized int balance() {        return balance;    }}
public class VolatileWalletDemo {    static void runFour(Runnable task) throws InterruptedException {        Thread[] ts = new Thread[4];        for (int i = 0; i < 4; i++) {            ts[i] = new Thread(task, "upi-" + (i + 1));            ts[i].start();        }        for (Thread t : ts) {            t.join();        }    }
    public static void main(String[] args) throws InterruptedException {        VolatileWallet wrong = new VolatileWallet();        runFour(() -> {            for (int i = 0; i < 100_000; i++) {                wrong.add(1);            }        });        System.out.println("Wrong: Rs " + wrong.balance + " (expected Rs 400000)");
        LockedWallet fixed = new LockedWallet();        runFour(() -> {            for (int i = 0; i < 100_000; i++) {                fixed.add(1);            }        });        System.out.println("Fixed: Rs " + fixed.balance() + " (expected Rs 400000)");    }}
Sample output
Wrong: Rs 368066 (expected Rs 400000)
Fixed: Rs 400000 (expected Rs 400000)

What this code does

  • balance += amount on a volatile field loses money: the wrong total changes from run to run and is usually short (now and then a run comes out right).
  • LockedWallet makes add synchronized, so the four threads take turns and the total is always Rs 400000.

Use volatile only when a write simply replaces the old value. When the new value depends on the old one, or two fields must change together, use a lock (or an atomic class, coming in the Locks & Atomic Variables module).

Mistake 3: unsafe lazy initialisation

if (instance == null) instance = new X(); without a lock is check-then-act: several threads can build several objects. Without a happens-before link, a thread may also see the reference before the object's fields.

Example 3 · Mistake: a rank list built four times

LazyInitMistakeDemo.javaJava
class Counter {    private int n = 0;
    synchronized void inc() {        n++;    }
    synchronized int get() {        return n;    }}
class RankListWrong {    static final Counter BUILT = new Counter();    private static RankListWrong instance;
    private RankListWrong() {        BUILT.inc();        pause();    }
    static RankListWrong get() {        if (instance == null) {            instance = new RankListWrong();        }        return instance;    }
    static void pause() {        try {            Thread.sleep(50);                     // pretend: sorts 10 lakh results        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }}
class RankListFixed {    static final Counter BUILT = new Counter();
    private RankListFixed() {        BUILT.inc();        RankListWrong.pause();    }
    private static class Holder {        static final RankListFixed INSTANCE = new RankListFixed();    }
    static RankListFixed get() {        return Holder.INSTANCE;    }}
public class LazyInitMistakeDemo {    static void runFour(Runnable task) throws InterruptedException {        Thread[] ts = new Thread[4];        for (int i = 0; i < 4; i++) {            ts[i] = new Thread(task, "student-" + (i + 1));            ts[i].start();        }        for (Thread t : ts) {            t.join();        }    }
    public static void main(String[] args) throws InterruptedException {        runFour(RankListWrong::get);        System.out.println("Wrong: rank lists built = " + RankListWrong.BUILT.get());        runFour(RankListFixed::get);        System.out.println("Fixed: rank lists built = " + RankListFixed.BUILT.get());    }}
Sample output
Wrong: rank lists built = 4
Fixed: rank lists built = 1

What this code does

  • Four students call get() while the first slow constructor is still running, so the bare null check lets each of them build its own rank list. The wrong count varies with timing.
  • The holder class idiom builds RankListFixed once, under the JVM's class setup lock, and every caller sees the finished object.

Fixes, from simplest: an enum singleton, the holder class idiom, a synchronized getter, or double-checked locking with a volatile field. Also watch for the other publication bug: letting this escape from a constructor.

Choosing the tool for each field

Choosing the tool is a per-field decision. Ask what kind of field it is, and the answer is almost always one of these.

Example 4 · One class, three tools: a cinema screen

CinemaToolsDemo.javaJava
record Show(String movie, String time, int price) {}
class Screen {    private volatile boolean bookingOpen = false;        // a flag: volatile    private volatile Show show = new Show("Jawan", "6:00 PM", 180);   // snapshot swap    private int seatsLeft = 120;                         // read-modify-write: lock
    void open() {        bookingOpen = true;    }
    boolean isOpen() {        return bookingOpen;    }
    Show show() {        return show;    }
    void changeShow(Show next) {        show = next;    }
    synchronized boolean book() {        if (seatsLeft == 0) {            return false;        }        seatsLeft--;        return true;    }
    synchronized int seatsLeft() {        return seatsLeft;    }}
public class CinemaToolsDemo {    public static void main(String[] args) throws InterruptedException {        Screen screen = new Screen();        int[] booked = new int[3];        Thread[] apps = new Thread[3];        for (int i = 0; i < 3; i++) {            int me = i;            apps[i] = new Thread(() -> {                while (!screen.isOpen()) {                    Thread.onSpinWait();                }                for (int k = 0; k < 50; k++) {                    if (screen.book()) {                        booked[me]++;                    }                }            }, "app-" + (i + 1));            apps[i].start();        }
        Thread.sleep(30);        screen.changeShow(new Show("Jawan", "9:30 PM", 220));        screen.open();        for (Thread a : apps) {            a.join();        }
        Show s = screen.show();        System.out.println(s.movie() + " at " + s.time() + ", Rs " + s.price());        System.out.println("booked: " + (booked[0] + booked[1] + booked[2]) + ", left: " + screen.seatsLeft());    }}
Output
Jawan at 9:30 PM, Rs 220
booked: 120, left: 0

What this code does

  • bookingOpen is a flag, so volatile. show is an immutable record swapped as a whole, so a volatile reference. seatsLeft is check-then-act, so synchronized methods.
  • Three apps try 150 bookings for 120 seats: exactly 120 succeed and none is sold twice, on every run.
  • A flag or status that is just replaced: volatile.
  • A counter, balance or check-then-act, or fields that change together: synchronized.
  • Data that rarely changes: an immutable object or record, swapped through a volatile reference.
  • A mutable helper each thread needs its own copy of: ThreadLocal (with remove() in reused threads), or an immutable replacement such as DateTimeFormatter.

Finish up

Mark complete & continue

Next: Why threads need to wait for each other