Immutability¶
Category: Safety in languages · Status: stub
One line: Data that cannot change after it is built can be shared by any number of threads with no synchronization at all.
Also called: immutable object, persistent data structure.
How it connects¶
flowchart LR
n_data_race["Data race"]
n_immutability["Immutability"]
n_immutability -->|prevents| n_data_race
classDef center stroke-width:3px
class n_immutability center
classDef outside stroke-dasharray: 4 3
class n_data_race outside
- Helps prevent: Data race
In each language¶
| Rust | The default: shared references disallow mutation ↗, so data behind an Arc changes only through a Mutex, RwLock or atomic inside it |
| Go | Strings are immutable ↗: once created, a string's contents cannot change |
| C++ | A const object ↗ cannot be modified, except for its mutable members |
| Java | JLS §17.5 final field semantics ↗ keep objects such as String immutable even when references to them cross threads through data races |
| Python | Frozen dataclasses ↗ raise FrozenInstanceError on assignment |
| C# | System.Collections.Immutable ↗ collections cannot be changed once created |
| JavaScript | Object.freeze ↗ is shallow: objects nested in a frozen object can still change |
Where to read more¶
- In the books: Concurrency in .NET, Riccardo Terrell — ch. 3, 'Functional data structures and immutability'
- In the books: Java Concurrency in Practice, Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, Doug Lea — ch. 3, 'Sharing Objects' → 'Immutability'
- In the books: Programming Concurrency on the JVM, Venkat Subramaniam — ch. 3, 'Design Approaches' → 'Purely Immutable Design'
- In the books: Concurrency in C# Cookbook, Stephen Cleary — ch. 9, 'Collections' → 'Immutable Stacks and Queues'
- In the books: Functional and Concurrent Programming, Michel Charpentier — ch. 19, 'Thread-Safe Objects' → 'Immutable Objects'
- Reference: Wikipedia: Immutable object ↗