Skip to content

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

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