Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added Foo definition to immutable CS

...

Compliant Solution (immutable)

If In this solution the Foo class is unchanged, but the Helper class is immutable, then it . In this case, the Helper class is guaranteed to be fully constructed before becoming visible. The object must be truly immutable; it is not sufficient for the program to refrain from modifying the object.

Code Block
bgColor#CCCCFF
public class Helper {
  private final int n;

  public Helper(int n) {
    this.n = n;
  }

  // other fields & methods, all fields are final
}


class Foo {
  private Helper helper = null;
  
  public Helper getHelper() { 
    if (helper == null) {
      synchronized(this) {
        if (helper == null) {
          helper = new Helper(); // If the helper is null, create a new instance
        }
      }
    }
    return helper; // If helper is non-null, return its instance
  }
}

Compliant Solution (static initialization)

...