Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This compliant solution uses a local variable to reduce the number of unsynchronized reads of the helper field to 1. As a result, if the read of helper yields a non-null value, it is cached in a local variable that is inaccessable to other threads, and safely returned.

Code Block
bgColor#ccccff
langjava
public final class Helper {
  private final int n;
 
  public Helper(int n) {
    this.n = n;
  }
 
  // Other fields and methods, all fields are final
}
 
final class Foo {
  private Helper helper = null;
 
  public Helper getHelper() {
    Helper h = helper;       // only one racyunsynchronized read of helper
    if (h == null) {
      synchronized (this) {
        h = helper;          // in synchronized block, so this is safe
        if (h == null) {
          h = new Helper(42);
          helper = h;
        }
      }
    }
    return h;
  }
}

...