Versions Compared

Key

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

...

Code Block
bgColor#FFCCCC
class Foo {
  private Helper helper;

  public Helper getHelper() {
    return helper;
  }

  public void initializesetHelper(int num) {
    helper = new Helper(num);
  }
}

...

Because the Helper class is immutable, it cannot be changed after it is initialized setHelperd and is therefore thread-safe.

However, because the helper field of class Foo is not properly synchronized, it is possible that the Foo.getHelper() method will return a reference to a partially or incorrectly initialized setHelperd helper object, if invoked from a separate thread.

...

This compliant solution synchronizes the methods of class Foo to ensure that no thread sees a partially initialized setHelperd helper field.

Code Block
bgColor#CCCCFF
class Foo {
  private Helper helper;

  public synchronized Helper getHelper() {
    return helper;
  }

  public synchronized void initializesetHelper(int num) {
    helper = new Helper(num);
  }
}

...

Code Block
bgColor#CCCCFF
class Foo {
  private volatile Helper helper;

  public Helper getHelper() {
    return helper;
  }

  public void initializesetHelper(int num) {
    helper = new Helper(num);
  }
}

...