Is this a safe publication?
Given the class:
@NotThreadSafe
public class Pub {
int drinkers;
public Pub(int drinkers) {
this.drinkers = drinkers;
}
}
T1 invokes publish() and T2 invokes inspect:
private final Object lock = new Object();
@GuardedBy("lock")
private Pub shared;
void publish() {
Pub p = new Pub(12);
synchronized(lock) {
this.shared = p; // publish
}
}
Pub inspect() {
synchronized(lock) {
return shared;
}
}
Is T2 guaranteed to see that shared.drinkers == 12? Or was the fact that we did not construct the Pub while holding the lock constitute an unsafe publication?
That’s a perfectly valid operation. Pub will either be null or initialised properly. This is because initialisation and assignment happen after each other on the same thread.