How to do it...

Follow these steps to implement an immutable class:

  1. Mark the class as final. It should not be extended by another class.
  2. All the attributes must be final and private. You can assign a value to an attribute only once.
  3. Don't provide methods that can assign a value to an attribute. Attributes must be initialized in the constructor of the class.
  1. If any field value object is mutable (for example, java.util.Date), always return a defensive copy in the getter field.
  2. Don't leak the this reference from the immutable class constructor (for example, the following code that leaks the this reference before the constructor is complete):
        public final NotSoImmutable implements Listener {           private final int x;  public NotSoImmutable(int ...

Get Java 9 Concurrency Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.