可能的重复:
如何模拟构造函数竞争条件? https://stackoverflow.com/questions/2614066/how-to-simulate-constructor-race-conditions
如何围绕未正确发布的值演示竞争条件? https://stackoverflow.com/questions/2624638/how-to-demonstrate-race-conditions-around-values-that-arent-published-properly
从《java并发实践》中得到如下代码:
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.");
}
}
我只是想知道条件n != n
,在某种情况下这可能是真的吗?
我的猜测是你问的问题与这些问题类似:
-
如何围绕未正确发布的值演示竞争条件? https://stackoverflow.com/questions/2624638/how-to-demonstrate-race-conditions-around-values-that-arent-published-properly
- 如何模拟构造函数竞争条件? https://stackoverflow.com/questions/2614066/how-to-simulate-constructor-race-conditions
我猜这本书正在讨论在对象完全构造之前共享对象引用的可能性,所提到的行为是不正确的发布。
假设n != n
分为以下步骤:
Access n on the right side of the operand
Access n on the left side of the operand
Compare values
那么不难想象这样一种情况:n
在前两个步骤之间发生了变化。现在我知道你在想什么,“但是n
永远不会改变”。实际上,确实如此,因为两个线程可以共享对一个实例的访问Holder
在该实例的构造函数完全运行之前。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)