...
| Code Block | ||
|---|---|---|
| ||
class Publisher {
public static Publisher pub;
int num;
Publisher(int number) {
// Initialization
this.num = number;
// ...
pub = this;
}
}
|
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 have executed.
...
Compliant Solution (volatile and publish after initialization)
This noncompliant code example compliant solution 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 | ||
|---|---|---|
| ||
class Publisher {
static volatile Publisher pub;
int num;
Publisher(int number) {
// Initialization
this.num = number;
// ...
pub = this;
}
}
|
The constructor publishes the this reference after initialization has concluded. However, it is unsuitable because a legit caller can the caller must ensure that it does not see the default value of the field, before it is initialized (a violation of CON26-J. Do not publish partially-constructed objects).
...