从Memory Consistancy Property起,我们知道: “将对象放入任何并发集合之前的一个线程中的操作发生 - 在从该集合中访问或从中删除该元素之后的操作另一个线程“。java.util.concurrent中的内存一致性
这是否意味着:如果我创建一个对象,并把它变成的ConcurrentLinkedQueue在一个线程,另一个线程会看到对象的所有属性没有物体上的其他同步?
例如:
public class Complex{
int index;
String name;
public Complex(int index, String name){
this.index = index;
this.name = name;
}
public String getName(){
return name;
}
public int getIndex(){
return index;
}
}
public class SharedQueue{
public static ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue();
}
在一个线程:
...........
Complex complex = new Complex(12, "Sam");
SharedQueue.queue.add(complex);
...... .....
在另一个线程
......
Complex complex = SharedQueue.queue.poll();
System.out.printly(complex.getIndex() + ";" + complex.getName());
.............
是否第二个线程一定会看到complex
对象的属性?如果第二个线程恰好获取对象并在第一个线程将该对象放入队列后将其打印出来。
我们知道,在正常情况下,我们应该在多线程环境中,如果它是同步共享对象。
像
public class Complex{
int index;
String name;
public Complex(int index, String name){
this.index = index;
this.name = name;
}
public synchronized String getName(){
return name;
}
public synchronized int getIndex(){
return index;
}
}
JLS在哪里指定了这个?众所周知的双重检查单例示例表明,如果没有适当的同步,其他线程可以观察到部分构建的对象。 – axtavt 2011-03-23 15:41:48
@axtavt,对不起,没有在JLS中,它在JSR 133中。 – 2011-03-23 15:52:57
JSR 133是JLS 3的内存模型,但它没有提供关于构造函数的任何保证(除'final'字段外)。 – axtavt 2011-03-23 15:57:17