O'Reilly logo

Java 9 Concurrency Cookbook - Second Edition by Javier Fernández González

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required