Why do immutable objects simplify concurrent code?
Options
- They are faster to create than mutable ones in every case
- They cannot change, so threads share them without locks (Correct option)
- They always use less memory than mutable objects do
- 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.