← Lessons

quiz vs the machine

Silver1050

Concurrency

Immutability for Thread Safety

Why objects that never change are automatically safe to share.

4 min read · intro · beat Silver to climb

Immutability for Thread Safety

An immutable object is one whose state cannot change after construction. Once built, its fields are fixed forever. This property turns out to be one of the simplest and most powerful tools in concurrent programming.

Data races happen when two threads access the same memory and at least one writes. If no thread can ever write, the race condition vanishes by definition. An immutable object can be shared across any number of threads with no locks and no defensive copying.

To make an object immutable:

  • Mark all fields final or read only so they are assigned once
  • Do not expose any method that mutates state
  • Make the class itself unmodifiable so subclasses cannot add mutable behavior
  • Copy any mutable inputs you store, and copy again on the way out

The cost is that every change produces a new object instead of editing the old one. For frequently updated data this creates garbage and pressure on memory. The benefit is that reasoning becomes trivial because a value you read can never be altered under your feet by another thread.

Immutable objects also publish safely. Once another thread sees a fully constructed immutable object through a proper handoff, it always sees consistent fields.

Key idea

If state never changes after construction, threads can share the object freely with no locks because there is nothing to race over.

Check yourself

Answer to earn rating on the learn ladder.

1. Why is an immutable object inherently thread safe?

2. What is a typical cost of immutability?