Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: made one class final

...

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 reference.

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

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

...

If the pub field is not declared as volatile initialization statements may be reordered. The Java compiler does not allow declaring the static pub field as final in this case.

The class Publisher should also be final, otherwise a subclass might execute its constructor and consequently, publish the this reference before the subclass's initialization has concluded.

Compliant Solution (public static factory method)

...