Java Concurrency Interview

Patterns and antipatterns question 149 of 180 junior

Why is immutability the strongest thread safety guarantee?

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.

design immutability

Quiz yourself on Patterns and antipatterns Suggest a correction