Patterncore
Immutable object
Also called immutable object, immutable, unchangeable object, value object.
An immutable object cannot change after its constructor ends. Threads can share it and read it with no lock, and an update makes a new object instead of a change to the shared one.
- Family
- concurrency
- Intent
- Make shared state safe for many threads by making it not mutable, so that each thread that holds a reference sees the same values for the whole life of the object.
- Also called
- Unchangeable object
Intent
An immutable object is an object whose state cannot be modified after it is created.1 Immutability tackles the shared-mutable-state cause of a race condition and solves it simply by making the shared state not mutable.2
Problem
Several threads read an object while another thread changes it. If the change writes two fields, a reader can run between the two writes and see the new value of one field with the old value of the other. A lock around every read and every write prevents this, but each reader then pays for the lock and waits for the writer.
Solution
Set all the state of the object in its constructor, and give the object no method that changes it. To change a value, make a new object and publish a reference to it. The MIT 6.031 reading gives a stronger definition of immutability for threads:2
- no mutator methods,
- all fields are private and final,
- no representation exposure,
- no mutation whatsoever of mutable objects in the representation, not even beneficent mutation such as a cache.2
reader 1 --+
reader 2 --+--> current --> Settings(8000) (never changes)
reader 3 --+ \
writer: current = Settings(8001) a new object; readers that hold
the old reference still see 8000
In Java, final fields allow programmers to implement thread-safe immutable objects without synchronization.3 A thread that can only see a reference to an object after its constructor finishes is guaranteed to see the correctly initialized values of the object's final fields.3
Example
The example has 4 readers that each read a shared Settings object 1000 times, and a writer that publishes 100 new objects. Each reader takes the current reference once and then checks that the port and the tag of that object agree.
reads: 4000
reads that saw a mixed pair: 0
settings published: 101
first settings unchanged: True
The examples for each language show the same program.
import threading
import time
from dataclasses import dataclass
@dataclass(frozen=True)
class Settings:
port: int
tag: str
first = Settings(8000, "port 8000")
current = first # readers take this reference; the writer replaces it
mixed = 0
reads = 0
lock = threading.Lock() # only for the counters of the demo
def reader():
global mixed, reads
for _ in range(1000):
s = current # one read of the reference gives a consistent snapshot
time.sleep(0) # let the writer run between the two field reads
ok = s.tag == f"port {s.port}"
with lock:
reads += 1
mixed += not ok
def writer():
global current
for port in range(8001, 8101):
current = Settings(port, f"port {port}") # a new object, never a change
time.sleep(0)
threads = [threading.Thread(target=reader) for _ in range(4)] + [threading.Thread(target=writer)]
for t in threads:
t.start()
for t in threads:
t.join()
print("reads:", reads)
print("reads that saw a mixed pair:", mixed)
print("settings published:", 1 + (current.port - first.port))
print("first settings unchanged:", first == Settings(8000, "port 8000"))
reads: 4000
reads that saw a mixed pair: 0
settings published: 101
first settings unchanged: True
- Verdict: stdlib.
@dataclass(frozen=True)makes assignment to a field raise an exception, and the writer publishes each newSettingsby one assignment tocurrent.
#include <atomic>
#include <iostream>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
struct Settings { // const members: set in the constructor, never changed
const int port;
const std::string tag;
Settings(int p, std::string t) : port(p), tag(std::move(t)) {}
};
std::mutex pointer_mutex; // guards only the pointer, not the object
std::shared_ptr<const Settings> current;
std::shared_ptr<const Settings> load() {
std::lock_guard<std::mutex> lock(pointer_mutex);
return current;
}
void publish(std::shared_ptr<const Settings> s) {
std::lock_guard<std::mutex> lock(pointer_mutex);
current = std::move(s);
}
int main() {
auto first = std::make_shared<const Settings>(8000, "port 8000");
publish(first);
std::atomic<int> reads{0}, mixed{0};
std::vector<std::thread> threads;
for (int i = 0; i < 4; i++) {
threads.emplace_back([&] {
for (int r = 0; r < 1000; r++) {
auto s = load(); // the object itself is read with no lock
std::this_thread::yield();
if (s->tag != "port " + std::to_string(s->port)) mixed++;
reads++;
}
});
}
threads.emplace_back([] {
for (int port = 8001; port <= 8100; port++) {
publish(std::make_shared<const Settings>(port, "port " + std::to_string(port)));
std::this_thread::yield();
}
});
for (auto& t : threads) t.join();
bool unchanged = first->port == 8000 && first->tag == "port 8000";
std::cout << "reads: " << reads << "\n";
std::cout << "reads that saw a mixed pair: " << mixed << "\n";
std::cout << "settings published: " << 1 + load()->port - first->port << "\n";
std::cout << "first settings unchanged: " << (unchanged ? "True" : "False") << "\n";
}
reads: 4000
reads that saw a mixed pair: 0
settings published: 101
first settings unchanged: True
- Verdict: idiom.
Settingshasconstmembers, the threads share it throughstd::shared_ptr<const Settings>, and a mutex guards only the copy of the pointer.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
static final class Settings { // final class, final fields, no setters
private final int port;
private final String tag;
Settings(int port, String tag) {
this.port = port;
this.tag = tag;
}
int port() { return port; }
String tag() { return tag; }
}
static final Settings first = new Settings(8000, "port 8000");
static volatile Settings current = first; // the writer replaces the reference
public static void main(String[] args) throws InterruptedException {
AtomicInteger reads = new AtomicInteger();
AtomicInteger mixed = new AtomicInteger();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 4; i++) {
threads.add(new Thread(() -> {
for (int r = 0; r < 1000; r++) {
Settings s = current; // one read gives a consistent snapshot
Thread.yield();
if (!s.tag().equals("port " + s.port())) mixed.incrementAndGet();
reads.incrementAndGet();
}
}));
}
threads.add(new Thread(() -> {
for (int port = 8001; port <= 8100; port++) {
current = new Settings(port, "port " + port); // a new object, never a change
Thread.yield();
}
}));
for (Thread t : threads) t.start();
for (Thread t : threads) t.join();
boolean unchanged = first.port() == 8000 && first.tag().equals("port 8000");
System.out.println("reads: " + reads.get());
System.out.println("reads that saw a mixed pair: " + mixed.get());
System.out.println("settings published: " + (1 + current.port() - first.port()));
System.out.println("first settings unchanged: " + (unchanged ? "True" : "False"));
}
}
reads: 4000
reads that saw a mixed pair: 0
settings published: 101
first settings unchanged: True
- Verdict: native.
Settingshas onlyfinalfields, which the Java memory model makes safe to read from any thread after the constructor ends, andvolatilepublishes each new reference.
using System;
using System.Collections.Generic;
using System.Threading;
sealed record Settings(int Port, string Tag); // positional record: init-only properties
class Program
{
static readonly Settings first = new Settings(8000, "port 8000");
static volatile Settings current = first; // the writer replaces the reference
static void Main()
{
int reads = 0, mixed = 0;
var threads = new List<Thread>();
for (int i = 0; i < 4; i++)
{
threads.Add(new Thread(() =>
{
for (int r = 0; r < 1000; r++)
{
Settings s = current; // one read gives a consistent snapshot
Thread.Yield();
if (s.Tag != "port " + s.Port) Interlocked.Increment(ref mixed);
Interlocked.Increment(ref reads);
}
}));
}
threads.Add(new Thread(() =>
{
for (int port = 8001; port <= 8100; port++)
{
current = new Settings(port, "port " + port); // a new object, never a change
Thread.Yield();
}
}));
foreach (var t in threads) t.Start();
foreach (var t in threads) t.Join();
Console.WriteLine("reads: " + reads);
Console.WriteLine("reads that saw a mixed pair: " + mixed);
Console.WriteLine("settings published: " + (1 + current.Port - first.Port));
Console.WriteLine("first settings unchanged: " + (first == new Settings(8000, "port 8000")));
}
}
reads: 4000
reads that saw a mixed pair: 0
settings published: 101
first settings unchanged: True
- Verdict: native. A positional
recordhas init-only properties, so aSettingscannot change after construction, and record equality compares the values.
"use strict"; // in strict mode, a write to a frozen object throws
function makeSettings(port) {
return Object.freeze({ port, tag: `port ${port}` });
}
const first = makeSettings(8000);
let current = first; // the writer replaces the reference
let reads = 0;
let mixed = 0;
const tick = () => new Promise((resolve) => setImmediate(resolve));
async function reader() {
for (let r = 0; r < 1000; r++) {
const s = current; // keep one snapshot across the await
await tick(); // the writer can run here
if (s.tag !== `port ${s.port}`) mixed += 1;
reads += 1;
}
}
async function writer() {
for (let port = 8001; port <= 8100; port++) {
current = makeSettings(port); // a new object, never a change
await tick();
}
}
Promise.all([reader(), reader(), reader(), reader(), writer()]).then(() => {
const unchanged = first.port === 8000 && first.tag === "port 8000";
console.log("reads:", reads);
console.log("reads that saw a mixed pair:", mixed);
console.log("settings published:", 1 + current.port - first.port);
console.log("first settings unchanged:", unchanged ? "True" : "False");
});
reads: 4000
reads that saw a mixed pair: 0
settings published: 101
first settings unchanged: True
- Verdict: stdlib.
Object.freezestops changes to theSettingsobjects, and the readers share them acrossawaitpoints on one event loop.
interface Settings {
readonly port: number;
readonly tag: string;
}
function makeSettings(port: number): Readonly<Settings> {
return Object.freeze({ port, tag: `port ${port}` });
}
const first = makeSettings(8000);
let current = first; // the writer replaces the reference
let reads = 0;
let mixed = 0;
const tick = (): Promise<void> => new Promise((resolve) => setImmediate(resolve));
async function reader(): Promise<void> {
for (let r = 0; r < 1000; r++) {
const s = current; // keep one snapshot across the await
await tick(); // the writer can run here
if (s.tag !== `port ${s.port}`) mixed += 1;
reads += 1;
}
}
async function writer(): Promise<void> {
for (let port = 8001; port <= 8100; port++) {
current = makeSettings(port); // a new object, never a change
await tick();
}
}
Promise.all([reader(), reader(), reader(), reader(), writer()]).then(() => {
const unchanged = first.port === 8000 && first.tag === "port 8000";
console.log("reads:", reads);
console.log("reads that saw a mixed pair:", mixed);
console.log("settings published:", 1 + current.port - first.port);
console.log("first settings unchanged:", unchanged ? "True" : "False");
});
reads: 4000
reads that saw a mixed pair: 0
settings published: 101
first settings unchanged: True
- Verdict: stdlib.
readonlyfields make the compiler reject writes,Object.freezestops them at run time, and the readers share the objects acrossawaitpoints.
package main
import (
"fmt"
"runtime"
"strconv"
"sync"
"sync/atomic"
)
// Settings has unexported fields and no methods that change them.
type Settings struct {
port int
tag string
}
func NewSettings(port int) *Settings {
return &Settings{port: port, tag: "port " + strconv.Itoa(port)}
}
func (s *Settings) Port() int { return s.port }
func (s *Settings) Tag() string { return s.tag }
func main() {
first := NewSettings(8000)
var current atomic.Pointer[Settings] // the writer replaces the pointer
current.Store(first)
var reads, mixed atomic.Int64
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for r := 0; r < 1000; r++ {
s := current.Load() // one load gives a consistent snapshot
runtime.Gosched()
if s.Tag() != "port "+strconv.Itoa(s.Port()) {
mixed.Add(1)
}
reads.Add(1)
}
}()
}
wg.Add(1)
go func() {
defer wg.Done()
for port := 8001; port <= 8100; port++ {
current.Store(NewSettings(port)) // a new object, never a change
runtime.Gosched()
}
}()
wg.Wait()
unchanged := "False"
if first.Port() == 8000 && first.Tag() == "port 8000" {
unchanged = "True"
}
fmt.Println("reads:", reads.Load())
fmt.Println("reads that saw a mixed pair:", mixed.Load())
fmt.Println("settings published:", 1+current.Load().Port()-first.Port())
fmt.Println("first settings unchanged:", unchanged)
}
reads: 4000
reads that saw a mixed pair: 0
settings published: 101
first settings unchanged: True
- Verdict: idiom.
Settingskeeps its fields unexported and has only read methods, andatomic.Pointerpublishes each new object.
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
struct Settings {
port: u32,
tag: String,
}
fn main() {
let first = Arc::new(Settings { port: 8000, tag: "port 8000".to_string() });
// Arc gives shared references only, so no thread can change a Settings.
let current = Arc::new(Mutex::new(Arc::clone(&first))); // guards only the pointer
let reads = Arc::new(AtomicUsize::new(0));
let mixed = Arc::new(AtomicUsize::new(0));
let mut threads = Vec::new();
for _ in 0..4 {
let (current, reads, mixed) = (Arc::clone(¤t), Arc::clone(&reads), Arc::clone(&mixed));
threads.push(thread::spawn(move || {
for _ in 0..1000 {
let s = Arc::clone(¤t.lock().unwrap()); // a consistent snapshot
thread::yield_now();
if s.tag != format!("port {}", s.port) {
mixed.fetch_add(1, Ordering::SeqCst);
}
reads.fetch_add(1, Ordering::SeqCst);
}
}));
}
{
let current = Arc::clone(¤t);
threads.push(thread::spawn(move || {
for port in 8001..=8100 {
let next = Arc::new(Settings { port, tag: format!("port {}", port) });
*current.lock().unwrap() = next; // a new object, never a change
thread::yield_now();
}
}));
}
for t in threads {
t.join().unwrap();
}
let last = Arc::clone(¤t.lock().unwrap());
let unchanged = first.port == 8000 && first.tag == "port 8000";
println!("reads: {}", reads.load(Ordering::SeqCst));
println!("reads that saw a mixed pair: {}", mixed.load(Ordering::SeqCst));
println!("settings published: {}", 1 + last.port - first.port);
println!("first settings unchanged: {}", if unchanged { "True" } else { "False" });
}
reads: 4000
reads that saw a mixed pair: 0
settings published: 101
first settings unchanged: True
- Verdict: native.
Arc<Settings>gives the threads shared references only, so the compiler rejects a write to a field of a sharedSettings; a mutex guards only theArcpointer.
Consequences
Benefits:
- Multiple threads can act on data represented by immutable objects without concern of the data being changed by other threads.1
- A program can copy a reference to an immutable object instead of the whole object. This conserves memory and avoids calls to constructors.1
- Immutable objects are simpler to understand and reason about than mutable objects.1
Liabilities:
- Each change makes a new object, and the writer must still publish the new reference safely. In Java, the constructor must not write a reference to the object being constructed in a place where another thread can see it before the constructor ends.3
- Immutability is a compile-time construct for the normal interface of the object. Code can still change the memory by circumventing the type system or violating const correctness in C or C++.1
- Hidden mutation, such as caching or lazy computation, is not safe for concurrency. An immutable type that uses it must make itself threadsafe using locks.2
A mutable object that the writer changes in place lets a reader see half of the update:
This code runs but gives a wrong answer on purpose.
import threading
class Settings: # mutable: the writer changes the shared object in place
def __init__(self, port):
self.port = port
self.tag = f"port {port}"
shared = Settings(8000)
half_done = threading.Event()
seen = threading.Event()
def writer():
shared.port = 8001
half_done.set()
seen.wait() # the reader runs between the two writes
shared.tag = "port 8001"
t = threading.Thread(target=writer)
t.start()
half_done.wait()
print("reader saw:", shared.port, "with tag", repr(shared.tag))
seen.set()
t.join()
reader saw: 8001 with tag 'port 8000'
When not to use it
Do not use an immutable object for large data that changes often in small steps, such as a big array that a loop updates one element at a time. Each step would copy the whole object. Keep such data confined to one thread, or guard it with a lock.
Variants and related patterns
- Weak and strong immutability. If only some fields cannot change, the object is weakly immutable. If all fields are immutable, the object is immutable, and if the class also cannot be extended, the object is called strongly immutable.1
- Copy with changes. A method returns a new object with some fields changed. Python's
dataclasses.replacecreates a new object of the same type, replacing fields with values from its arguments.4 Withfrozen=True, assigning to fields generates an exception.4
from dataclasses import FrozenInstanceError, dataclass, replace
@dataclass(frozen=True)
class Settings:
port: int
tag: str
s = Settings(8000, "port 8000")
try:
s.port = 9000
except FrozenInstanceError:
print("assignment to a field: FrozenInstanceError")
t = replace(s, port=9000, tag="port 9000") # a changed copy
print("old:", s.port, s.tag)
print("new:", t.port, t.tag)
assignment to a field: FrozenInstanceError
old: 8000 port 8000
new: 9000 port 9000
- Copy-on-write. The system shares one object until a user modifies it, and then makes a real copy for that user.1 The copy-on-write page describes this pattern for threads.
Thread confinement is the other way to avoid a lock: it does not share the mutable state at all.2
Known uses
- In Python, Java and the .NET Framework, strings are immutable objects.1
- All the primitive wrapper classes in Java are immutable.1
- In Python, numbers, Booleans, strings, tuples and frozensets are immutable.1
- C# has records, which are immutable.1
References
- Immutable object, Wikipedia, lead; Weak vs strong immutability; Referencing vs copying objects; Thread safety; Violating immutability; Language-specific details
- MIT 6.031 Software Construction, Reading 20: Thread Safety, Strategy 2, Immutability
- The Java Language Specification, Java SE 21, Chapter 17 Threads and Locks, 17.5 final Field Semantics
- dataclasses, Data Classes, Python documentation, @dataclass, frozen; replace(); FrozenInstanceError
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag QTM1MV Edit this page History Report an error Markdown