Repaso
Español
Design & PracticesIntermediateDP-20

Why do immutable objects simplify concurrent code?

Options

  1. They are faster to create than mutable ones in every case
  2. They cannot change, so threads share them without locks (Correct option)
  3. They always use less memory than mutable objects do
  4. They are automatically saved to the database when created

Answer

They cannot be changed after creation, so threads can share them without locks

Why

Most concurrency bugs come from two threads changing the same data at the same time (race conditions).

An immutable object can never change, so any number of threads can read it at once with no risk and no locks.

To 'modify' it you create a new object, which other threads never see half-finished.

Remember

No changes → no race conditions.

Key terms

Practice this question in Repaso