// 不安全的發(fā)布
public Holder holder;
public void initialize() {
holder = new Holder(42);
}
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.5 節(jié)中有一段非常反直覺的代碼,大意是說(shuō)如果采用上面的初始化方式赫舒,另一個(gè)線程調(diào)用 assertSanity
方法時(shí)可能會(huì)拋 AssertionError
蚤霞,不知道時(shí)水平不夠還是翻譯有問題, 這段我想了久沒有想明白镣煮,后來(lái)在 stack overflow 上找到了對(duì)這段代碼的解釋奈搜。 https://stackoverflow.com/questions/1621435/not-thread-safe-object-publishing
The reason why this is possible is that Java has a weak memory model. It does not guarantee ordering of read and writes.
This particular problem can be reproduced with the following two code snippets representing two threads.
Thread 1:
someStaticVariable = new Holder(42);
Thread 2:
someStaticVariable.assertSanity(); // can throw
On the surface it seems impossible that this could ever occur. In order to understand why this can happen, you have to get past the Java syntax and get down to a much lower level. If you look at the code for thread 1, it can essentially be broken down into a series of memory writes and allocations:
- Alloc memory to pointer1
- Write 42 to pointer1 at offset 0
- Write pointer1 to someStaticVariable
Because Java has a weak memory model, it is perfectly possible for the code to actually execute in the following order from the perspective of thread 2:
- Alloc Memory to pointer1
- Write pointer1 to someStaticVariable
- Write 42 to pointer1 at offset 0
Scary? Yes but it can happen.
What this means though is that thread 2 can now call into
assertSanity
beforen
has gotten the value 42. It is possible for the valuen
to be read twice duringassertSanity
, once before operation #3 completes and once after and hence see two different values and throw an exception.EDIT
According to Jon Skeet, the
AssertionError
migh still occur with Java 8 unless the field is final.
出現(xiàn)這種情況是因?yàn)?JVM 的重排序引起的,這句初始化代碼 someStaticVariable = new Holder(42);
可以分為三步 1. 申請(qǐng)內(nèi)存 2. 對(duì) n 賦值 3. 把引用賦值給 someStaticVariable盯荤。因?yàn)橹嘏判蚩赡艽騺y這三不的循序馋吗。可能會(huì)出現(xiàn)秋秤,已經(jīng)把引用賦值 someStaticVariable 變量了宏粤,但是 n 還沒有賦值的情況,而 assertSanity 中的一個(gè) n 讀的是賦值前的數(shù)據(jù)灼卢,一個(gè)是讀賦值后的數(shù)據(jù)所以不相等绍哎。