Video in progress

What does it mean for a class to be "thread-safe", and how do immutable objects help with that?

A thread-safe class works correctly when several threads use it at the same time, without extra synchronization. An immutable object never changes its state, so it is automatically thread-safe.

📖 Answer

Thread-safety is achieved in three ways: don't share state, don't change state, or synchronize access. The cheapest is the second one.

public record Money(BigDecimal amount, String currency) {
    public Money plus(Money other) {
        return new Money(amount.add(other.amount), currency);  // a new object
    }
}

You can hand this record to as many threads as you like, and nobody can break it. A "modification" creates a new object.

To be fully immutable:

  • all fields are final;
  • there are no setters;
  • mutable objects inside (List, Date) don't escape; they are copied with List.copyOf(...);
  • this is not passed to another thread from inside the constructor.

Watch out: final List<String> items is not immutable yet. The reference doesn't change, but you can still add to the list.

In practice, if you make DTOs, configuration and value objects immutable, a large share of concurrency problems disappears on its own.