Patterns and antipatterns question 149 of 180 junior
Why is immutability the strongest thread safety guarantee?
- Because immutable objects are faster
- Correct: Because state that never changes cannot race: all-final fields are safely published by any means, with no synchronisation at all
- Because the GC handles them specially
- Because they cannot be null
An immutable object has no writes after construction, so there is nothing for two threads to disagree about. The final-field guarantee means that any thread obtaining a reference sees the fields fully constructed, even through a data race, so you can share it freely.
The requirements are exact: all fields final, no setters, this never escaping the constructor, and
defensive copies of any mutable component both in and out. A final List field is not enough; the list
must be List.copyOf'd or wrapped.
Records give you most of this for free, with the caveat that a record holding a mutable array or list is only as immutable as its components.
Quiz yourself on Patterns and antipatterns Suggest a correction