清单3.15。如果未正确发布,则有失败的风险。
public class Holder {
private int n;
public Holder(int n) { this.n = n; }
public void assertSanity() {
if (n != n)
throw new AssertionError("This statement is false.");
}
}
如果清单3.15中的持有者是使用清单3.14中不安全的发布习惯用法发布的,则
其他
发布线程调用assertSanity时,可能会抛出assertonerror!
[15]
清单3.14。在没有足够同步的情况下发布对象。别这样。
// Unsafe publication
public Holder holder;
public void initialize() {
holder = new Holder(42);
}
a)第一个查询与
发布线程本身
,没有其他线程。如果发布线程执行如下操作-
1. Holder holder = new Holder (5);
2. holder.getN() // is it guaranteed that this will print 5
根据程序顺序规则。线程中的每个操作都发生在
该线程中的每个操作都是按程序顺序进行的。
自从
1 hb 2
根据上述规则,2将能够正确地看到obj对持有者的转让。
但是否保证2号也能看到持物体的安全构造
不在n声明前加最后一个修饰符
?
做
public Holder(int n) { this.n = n; }
血红蛋白
1
?