这是一份安全的出版物吗?
给定班级:
@NotThreadSafe
public class Pub {
int drinkers;
public Pub(int drinkers) {
this.drinkers = drinkers;
}
}
T1 调用publish()
和 T2 调用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;
}
}
T2 能保证看到shared.drinkers == 12
吗?还是我们在持有锁时没有构建Pub 的事实构成了不安全的发布?