Share immutable objects safely
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)An immutable object is one whose state can never change after its constructor finishes. Any number of threads can read it at the same time with no locks, because there is no write to race with and no old value to go stale.
Why immutable objects need no locks
Immutable objects need no locks because every thread problem so far needed a write: lost updates, stale flags, half-done changes. If nothing can be written after construction, none of them can happen.
Example 1 · One immutable marksheet, three threads, no locks
final class Marksheet { // final: no subclass can add mutable state private final String name; private final int maths; private final int physics; private final int chemistry;
Marksheet(String name, int maths, int physics, int chemistry) { this.name = name; this.maths = maths; this.physics = physics; this.chemistry = chemistry; }
String name() { return name; }
int total() { return maths + physics + chemistry; }
int best() { return Math.max(maths, Math.max(physics, chemistry)); }}
public class ImmutableMarksheetDemo { public static void main(String[] args) throws InterruptedException { Marksheet sheet = new Marksheet("Kavya", 92, 81, 88); String[] reports = new String[3];
Thread total = new Thread(() -> reports[0] = "total: " + sheet.total(), "total"); Thread best = new Thread(() -> reports[1] = "best: " + sheet.best(), "best"); Thread percent = new Thread( () -> reports[2] = "percent: " + sheet.total() * 100 / 300 + "%", "percent");
total.start(); best.start(); percent.start(); total.join(); best.join(); percent.join();
System.out.println(sheet.name()); for (String r : reports) { System.out.println(" " + r); } }}Kavya total: 261 best: 92 percent: 87%
What this code does
Marksheetisfinal, its fields areprivate finaland it has no setters. The three threads read it at the same time without anysynchronizedorvolatile.- The sheet was built before the threads started, and each thread writes only its own array slot, read by main after
join(), so the output is the same on every run.
- All fields are
private final, and there are no setters. - The class is
final, so no subclass can add changing state. - Mutable inputs (lists, arrays) are copied in, and never handed out to be changed.
thisdoes not escape from the constructor.
A class is immutable when it follows a few rules. Its final fields also give it the final field promise from the last lesson, so even a reference shared carelessly shows the right values.
Records and final fields as shared data
A record (Java 16) is a short way to write an immutable data class: record Fare(String route, int amount) {} gets private final fields, a constructor, getters, equals, hashCode and toString. A compact constructor (Fare { ... }) lets you check the inputs.
Example 2 · A record as shared data, changed by making a new one
record Fare(String route, String travelClass, int amount) { Fare { // compact constructor: checks input if (amount < 0) { throw new IllegalArgumentException("negative fare"); } }
Fare withAmount(int newAmount) { // "change" = a new record return new Fare(route, travelClass, newAmount); }}
public class RecordFareDemo { public static void main(String[] args) throws InterruptedException { Fare normal = new Fare("Pune-Mumbai", "CC", 485);
Thread tatkal = new Thread(() -> { Fare surge = normal.withAmount(normal.amount() + 120); System.out.println("tatkal thread: " + surge); }, "tatkal"); tatkal.start(); tatkal.join();
System.out.println("original: " + normal); System.out.println("equal? " + normal.equals(new Fare("Pune-Mumbai", "CC", 485))); }}tatkal thread: Fare[route=Pune-Mumbai, travelClass=CC, amount=605] original: Fare[route=Pune-Mumbai, travelClass=CC, amount=485] equal? true
What this code does
- The Tatkal thread builds a new
FarewithwithAmount; the originalnormalfare is untouched, so any other thread still using it sees 485. - The record gives
toStringand value-basedequalsfor free, and the compact constructor rejects a negative fare.
To "change" a record, you create a new one with the new value, often with a method named withAmount or similar. Threads holding the old record keep a consistent old value; nobody's object changes under their feet.
Predict the output
Predict the output
Records and copied lists never change after they are made. Pick the exact output.
Round 1 of 2
Two records with the same values.
List component can still be changed through the list itself; the last section fixes that.Replace the whole object behind a volatile reference
Snapshot swapping is how you update shared settings without locks for readers: keep the settings in one immutable object, and keep a volatile reference to it. To update, build a complete new object and assign it to the reference in one write.
Example 3 · Mistake: updating settings one field at a time
class TatkalSettings { private volatile String openTime = "10:00"; private volatile int maxTickets = 4;
void setOpenTime(String t) { openTime = t; }
void setMaxTickets(int n) { maxTickets = n; }
String describe() { return "opens " + openTime + ", max " + maxTickets + " tickets"; }}
public class MutableSettingsMistakeDemo { public static void main(String[] args) throws InterruptedException { TatkalSettings settings = new TatkalSettings();
Thread admin = new Thread(() -> { try { settings.setOpenTime("11:00"); // AC Tatkal rule, part 1 Thread.sleep(50); // makes the gap easy to see settings.setMaxTickets(6); // part 2 } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, "admin"); admin.start();
Thread.sleep(20); System.out.println("booking sees: " + settings.describe()); admin.join(); System.out.println("after update: " + settings.describe()); }}booking sees: opens 11:00, max 4 tickets after update: opens 11:00, max 6 tickets
What this code does
- Both fields are
volatile, so each one is visible, yet the booking thread sees the new opening time with the old ticket limit: a mix that never existed as a rule. The sleep only widens the gap so you can see it every time. volatilekeeps single fields fresh; it cannot keep two fields in step. That needs one object that holds both.
Example 4 · Swapping an immutable snapshot
record TatkalRules(String openTime, int maxTickets) {}
class RulesHolder { private volatile TatkalRules current = new TatkalRules("10:00", 4);
TatkalRules current() { return current; }
void replace(TatkalRules next) { current = next; }}
public class SnapshotSwapDemo { public static void main(String[] args) throws InterruptedException { RulesHolder holder = new RulesHolder();
Thread booking = new Thread(() -> { TatkalRules first = holder.current(); // read the reference once System.out.println("booking uses: " + first); TatkalRules next; while ((next = holder.current()) == first) { Thread.onSpinWait(); } System.out.println("booking uses: " + next); }, "booking"); booking.start();
Thread.sleep(30); TatkalRules updated = new TatkalRules("11:00", 6); // build the whole new state holder.replace(updated); // then publish it in one write booking.join(); }}booking uses: TatkalRules[openTime=10:00, maxTickets=4] booking uses: TatkalRules[openTime=11:00, maxTickets=6]
What this code does
- The admin builds the whole new
TatkalRulesfirst and publishes it with one volatile write. The booking thread sees either10:00, 4or11:00, 6, never a mix. - The reader takes the reference once into a local variable (
first,next) and uses only that, so even a swap in the middle of its work cannot change what it is using.
A reader reads the reference once into a local variable and uses only that. It sees either the whole old settings or the whole new settings, never a mix, which a mutable object updated field by field cannot promise. With one writer, a plain assignment is enough. With several writers that build the new value from the old one, the update is read-modify-write again, so make the update method synchronized (readers still need no lock).
List.copyOf and unmodifiable views
List.copyOf(list) (Java 10) returns an unmodifiable copy: later changes to the original do not show in it, and calling add or remove on it throws UnsupportedOperationException. List.of(...) builds the same kind of list from values.
Example 5 · List.copyOf versus an unmodifiable view
import java.util.ArrayList;import java.util.Collections;import java.util.List;
public class CopyOfVsViewDemo { public static void main(String[] args) { List<String> toppers = new ArrayList<>(List.of("Aditi", "Rohan"));
List<String> view = Collections.unmodifiableList(toppers); // read-only window List<String> copy = List.copyOf(toppers); // frozen copy
toppers.add("Sneha"); // change the original
System.out.println("original: " + toppers); System.out.println("view: " + view); System.out.println("copy: " + copy);
try { copy.add("Imran"); } catch (UnsupportedOperationException e) { System.out.println("copy.add -> UnsupportedOperationException"); } try { view.add("Imran"); } catch (UnsupportedOperationException e) { System.out.println("view.add -> UnsupportedOperationException"); } }}original: [Aditi, Rohan, Sneha] view: [Aditi, Rohan, Sneha] copy: [Aditi, Rohan] copy.add -> UnsupportedOperationException view.add -> UnsupportedOperationException
What this code does
Snehawas added to the original after both were made. The view shows her, because it is a window onto the original; the copy does not.- Both refuse
addwithUnsupportedOperationException. Only the copy is truly frozen.
Example 6 · A record with a list: copy it in
import java.util.ArrayList;import java.util.List;
record LeakyBatch(String name, List<String> students) {}
record SafeBatch(String name, List<String> students) { SafeBatch { students = List.copyOf(students); // copy in, unmodifiable }}
public class RecordListLeakDemo { public static void main(String[] args) { List<String> names = new ArrayList<>(List.of("Arjun", "Bela"));
LeakyBatch leaky = new LeakyBatch("CSE-A", names); SafeBatch safe = new SafeBatch("CSE-A", names);
names.add("Charu"); // someone keeps using the old list
System.out.println("leaky: " + leaky.students()); System.out.println("safe: " + safe.students()); }}leaky: [Arjun, Bela, Charu] safe: [Arjun, Bela]
What this code does
LeakyBatchstores the caller'sArrayList, so when the caller addsCharu, the "immutable" record changes too.SafeBatchcopies the list in its compact constructor withList.copyOf, so it keeps the two names it was given and nobody can add to it.
- Freeze data you will share or store:
List.copyOf,Set.copyOf,Map.copyOf. - Copy lists in a record's compact constructor:
items = List.copyOf(items);. List.copyOfdoes not allownullelements; it throwsNullPointerException.- The elements must be immutable too: a frozen list of mutable objects is not frozen data.
Collections.unmodifiableList(list) returns a read-only view: you cannot change the list through it, but it shows every change made to the original. A view of a list that some thread still changes is not immutable and not safe to share.
Next step
Check your understanding
11 quick questions