Versions Compared

Key

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

...

Because, the field is nonvolatile and nonfinal, the statements within the constructor can be reordered by the compiler in such a way that the this reference is published before the initialization statements are have executed.

Noncompliant Code Example (visibility of partially initialized object)

This noncompliant code example declares the pub field as volatile and reduces the accessibility of the static class field to package-private so that untrusted callers beyond the current package cannot obtain the this instance reference.

Code Block
bgColor#FFcccc
class Publisher {
  static volatile Publisher pub;
  int num;

  Publisher(int number) {
    // Initialization 
    this.num = number;
    // ...
    pub = this;
  }
}

...

This compliant solution removes the internal field and provides a newInstance() factory method which can be used to obtain an instance of the Publisher object. This ensures that threads do not see a compromised Publisher instance.

Code Block
bgColor#ccccff
class Publisher {
  final int num;

  private Publisher(int number) {
    // Initialization 
    this.num = number;
  }
  
  public static Publisher newInstance(int number) {
    Publisher pu = new Publisher(number);  
    return pu;
  }
}

This ensures that threads do not see a compromised Publisher instance. The num variable is also declared as {final.

Noncompliant Code Example (handlers)

...