Building immutable classes in Java 9
So far, we have been working with mutable classes and mutating objects. Whenever we expose mutable fields, we create a class that will generate mutable instances. In certain scenarios, we might prefer an object that cannot change its state after it has been initialized. We can design classes to be immutable and to generate immutable instances that cannot change their state after they were created and initialized.
A typical scenario where immutable objects are extremely useful is when we work with concurrent code. Objects that cannot change their state solve many typical concurrency problems and avoid potential bugs that might be difficult to detect and solve. Because immutable objects cannot change their state, it is not possible to end up with an object with a corrupted or inconsistent state when many different threads modify it without the appropriate synchronization mechanisms.
Note
An immutable object is also known as a non-mutating object.
We will create...