Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added disclaimer on CAS CS

...

Code Block
bgColor#ccccff
// Uses atomic utilities
class Foo {
  private final AtomicReference<Helper> helperRef =
    new AtomicReference<Helper>();

  public Helper getHelper() {
    Helper helper = helperRef.get();
    if (helper != null) {
      return helper;
    }
    Helper newHelper = new Helper();
    return helperRef.compareAndSet(null, newHelper) ?
           newHelper :
           helperRef.get();
  }
}

Note that while this code ensures that only one Helper}] object is preserved, it may potentially allow multiple {{Helper objects to be created; with all but one being garbage-collected. But if constructing multiple Helper objects is infeasible or expensive, then this solution might not be appropriate.

Compliant Solution (immutable)

...