Search code examples
javaimmutabilityeffective-java

Immutable in java


In Effective Java, Bloch recommends to make all the fields final in making an object immutable .

Is it necessary to do so ? Won't just not giving accessor methods make it immutable.

For example

class A {
      private int x;
      A (int x) {
          this.x = x;
      }
}

The above class is immutable even if I don't declare x as final right ? Am I missing something ?


Solution

  • In addition to @Bozho's point, declaring a field as final means that it can be safely accessed without any synchronization.

    By contrast, if the field is not final there is a small risk that another thread will see an anomalous value for the field if it accesses it without proper synchronization. This can happen even if nothing changes the field's value after object construction!