Design a thread-safe class
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Other developers will share your Account object between threads and cannot be expected to add locks around every call. How do you design the class so that it is safe by itself?
Invariants and the lock that guards them
A class is thread-safe when it behaves correctly even if many threads use the same object at the same time, without the caller adding extra locking.
An invariant is a rule about an object's data that must always be true when no method is running: balance >= 0, min <= max, or free + booked == totalSeats. A thread-safe class is one whose invariants hold no matter how threads interleave.
Example 1 · An invariant that always holds under one lock
class SeatMap { private static final int TOTAL = 1_000_000; private final Object lock = new Object(); private int free = TOTAL; // guarded by lock: free + booked == TOTAL private int booked = 0;
void book() { synchronized (lock) { if (free > 0) { free--; // the invariant is broken for a moment here... booked++; // ...and fixed again before the lock is released } } }
boolean invariantHolds() { synchronized (lock) { return free + booked == TOTAL; } }
String status() { synchronized (lock) { return "free " + free + ", booked " + booked; } }}
public class LockedInvariantDemo { public static void main(String[] args) throws InterruptedException { SeatMap map = new SeatMap(); int[] violations = new int[1]; Runnable booker = () -> { for (int i = 0; i < 500_000; i++) { map.book(); } }; Thread b1 = new Thread(booker, "booker-1"); Thread b2 = new Thread(booker, "booker-2"); Thread checker = new Thread(() -> { while (b1.isAlive() || b2.isAlive()) { if (!map.invariantHolds()) { violations[0]++; } } }, "checker"); b1.start(); b2.start(); checker.start(); b1.join(); b2.join(); checker.join(); System.out.println("Invariant violations seen: " + violations[0]); System.out.println("Final: " + map.status()); }}Invariant violations seen: 0 Final: free 0, booked 1000000
What this code does
- The checker thread tests
free + booked == TOTALagain and again for as long as the two booking threads are alive (isAlive()). Because the check takes the same lock asbook(), it can never land betweenfree--andbooked++, so it sees 0 violations on every run. - The comment
// guarded by locknext to the fields records which lock protects them and which rule they share.
Every invariant gets one lock that guards all the fields it mentions. If free and booked must add up to the total, both are changed and read under the same lock, in the same block. While a method runs, the invariant may be broken for a moment (after free--, before booked++), but no other thread can see that moment. Write the rule down next to the fields, for example // guarded by lock: free + booked == TOTAL. It tells every future reader which lock to use.
Reads need the lock too
A consistent read sees the data either before or after an update, never in the middle. Without the lock, a reader can run between two writes of an update and see a state that breaks the invariant.
Example 2 · Mistake: reading without the lock
class SeatMap { private static final int TOTAL = 1_000_000; private final Object lock = new Object(); private int free = TOTAL; private int booked = 0;
void book() { synchronized (lock) { if (free > 0) { free--; booked++; } } }
boolean invariantHoldsNoLock() { // the bug: no lock return free + booked == TOTAL; }}
public class UnlockedReadDemo { public static void main(String[] args) throws InterruptedException { SeatMap map = new SeatMap(); int[] violations = new int[1]; Runnable booker = () -> { for (int i = 0; i < 500_000; i++) { map.book(); } }; Thread b1 = new Thread(booker, "booker-1"); Thread b2 = new Thread(booker, "booker-2"); Thread checker = new Thread(() -> { while (b1.isAlive() || b2.isAlive()) { // check for as long as booking runs if (!map.invariantHoldsNoLock()) { violations[0]++; } } }, "checker"); b1.start(); b2.start(); checker.start(); b1.join(); b2.join(); checker.join(); System.out.println("Invariant violations seen: " + violations[0]); }}Invariant violations seen: 1551
What this code does
- All writes are still locked, but the checker reads without the lock. Sometimes it reads
freeafter one booking'sfree--andbookedbefore itsbooked++, and sees one seat missing. The count changes from run to run. - The data was never really wrong; the reader just looked in the middle of an update. A screen or report built from such reads shows numbers that never existed together.
There is a second reason. Without a lock (or another tool from the Visibility module), Java does not promise that a reading thread sees the latest values written by other threads at all. A read taken under the same lock as the writes always sees the latest completed update. So every getter that reads guarded fields uses the same lock as the writers. If a caller needs several values that belong together, return them together from one locked method, for example as a small record.
Encapsulation: never leak the mutable state
Encapsulation here means that no code outside the class can reach the guarded data except through methods that take the lock.
Example 3 · Mistake: a getter that leaks the internal list
import java.util.ArrayList;import java.util.ConcurrentModificationException;import java.util.List;
class OrderBook { private final Object lock = new Object(); private final List<String> orders = new ArrayList<>();
void add(String order) { synchronized (lock) { orders.add(order); } }
List<String> getOrders() { synchronized (lock) { return orders; // leaks the real list } }}
public class LeakedListDemo { public static void main(String[] args) throws InterruptedException { OrderBook book = new OrderBook(); for (int i = 1; i <= 50; i++) { book.add("order-" + i); } Thread packer = new Thread(() -> { for (int i = 51; i <= 100; i++) { book.add("order-" + i); pause(1); } }, "packer"); packer.start(); try { for (String order : book.getOrders()) { // iterating with no lock held pause(1); } System.out.println("Report finished"); } catch (ConcurrentModificationException e) { System.out.println("Report failed: " + e.getClass().getSimpleName()); } packer.join(); }
static void pause(int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }}Report failed: ConcurrentModificationException
What this code does
getOrders()takes the lock, but only while it returns the reference. The loop then walks the real list with no lock while thepackerthread keeps adding, soArrayListnotices the change and throwsConcurrentModificationException(on almost every run).- Worse failures are possible too: a caller could call
addorclearon the leaked list and skip the lock completely.
Example 4 · The fix: return an unmodifiable copy
import java.util.ArrayList;import java.util.List;
class OrderBook { private final Object lock = new Object(); private final List<String> orders = new ArrayList<>(); // guarded by lock
void add(String order) { synchronized (lock) { orders.add(order); } }
List<String> getOrders() { synchronized (lock) { return List.copyOf(orders); // a copy made under the lock } }}
public class SafeCopyDemo { public static void main(String[] args) throws InterruptedException { OrderBook book = new OrderBook(); for (int i = 1; i <= 50; i++) { book.add("order-" + i); } Thread packer = new Thread(() -> { for (int i = 51; i <= 100; i++) { book.add("order-" + i); } }, "packer"); packer.start();
List<String> report = book.getOrders(); int counted = 0; for (String order : report) { counted++; } System.out.println("Report finished: " + (counted == report.size())); try { report.add("fake-order"); } catch (UnsupportedOperationException e) { System.out.println("Cannot change the copy: " + e.getClass().getSimpleName()); } packer.join(); System.out.println("Orders in the book: " + book.getOrders().size()); }}Report finished: true Cannot change the copy: UnsupportedOperationException Orders in the book: 100
What this code does
- The report walks its own copy, so the packer thread can keep adding with no exception. The copy may hold anywhere from 50 to 100 orders depending on timing, which is why the program prints only that the loop finished.
List.copyOfreturns an unmodifiable list, so callers cannot change the book behind its lock. Afterjoin(), the book holds all 100 orders.
State leaks through public or package-private fields, getters that return an internal List, Map or array, and constructors that hand this to another thread before they finish. If a reference to an internal list or array escapes, other code can change or read it with no lock at all, and your careful locking is bypassed.
The fixes are simple: make fields private, and return copies, such as List.copyOf(items) made under the lock. List.copyOf (Java 10) returns an unmodifiable copy: callers can read it freely, and any attempt to change it throws UnsupportedOperationException.
A thread-safe bank account step by step
Putting it together, a thread-safe class design follows four steps. The bank account below follows them.
- Find the state:
balance, the transaction count and the statement lines. The holder's name never changes, so it isfinaland needs no lock. - Write the invariants:
balance >= 0, and one statement line per transaction. - Pick one private lock for all fields that share an invariant, and use it in every method that reads or writes them, including getters.
- Keep the state private, validate inside the lock, return copies, and make the class
finalso a subclass cannot add unlocked methods.
Example 5 · A thread-safe bank account
import java.util.ArrayList;import java.util.List;
final class BankAccount { private final String holder; private final Object lock = new Object(); private int balance; // guarded by lock: balance >= 0 private final List<String> statement = new ArrayList<>(); // guarded by lock
BankAccount(String holder, int opening) { if (opening < 0) { throw new IllegalArgumentException("opening balance must not be negative"); } this.holder = holder; this.balance = opening; }
void deposit(int amount) { if (amount <= 0) { throw new IllegalArgumentException("amount must be positive"); } synchronized (lock) { balance += amount; statement.add("+" + amount); } }
boolean withdraw(int amount) { if (amount <= 0) { throw new IllegalArgumentException("amount must be positive"); } synchronized (lock) { if (balance < amount) { // check and act under one lock return false; } balance -= amount; statement.add("-" + amount); return true; } }
int balance() { synchronized (lock) { return balance; } }
List<String> statement() { synchronized (lock) { return List.copyOf(statement); } }
String holder() { return holder; }}
public class BankAccountDemo { public static void main(String[] args) throws InterruptedException { BankAccount acc = new BankAccount("Priya", 100_000); Thread salary = new Thread(() -> { for (int i = 0; i < 1000; i++) acc.deposit(100); }, "salary"); Thread upi = new Thread(() -> { for (int i = 0; i < 1000; i++) acc.withdraw(40); }, "upi"); Thread atm = new Thread(() -> { for (int i = 0; i < 1000; i++) acc.withdraw(60); }, "atm"); salary.start(); upi.start(); atm.start(); salary.join(); upi.join(); atm.join();
System.out.println(acc.holder() + "'s balance: Rs " + acc.balance()); System.out.println("Statement lines: " + acc.statement().size()); try { acc.deposit(-500); } catch (IllegalArgumentException e) { System.out.println("Rejected: " + e.getMessage()); } System.out.println("Overdraft allowed? " + acc.withdraw(1_000_000)); }}Priya's balance: Rs 100000 Statement lines: 3000 Rejected: amount must be positive Overdraft allowed? false
What this code does
holdernever changes, so it needs no lock. Every field that shares an invariant is private and guarded by one lock, and every method that reads or writes them takes it.withdrawchecks and subtracts in one block, sobalancecan never go below 0, and the statement always has one line per transaction.- Argument checks run before the lock, since they touch no shared data. The opening balance is large enough that no withdrawal can fail in any order, so the result is the same on every run: +100,000 − 40,000 − 60,000 leaves Rs 100,000.
Next step
Check your understanding
11 quick questions