我想确保根据Java内存模型正确理解“有效不可变对象”行为。有效不可变对象
比方说,我们有我们要发布为有效不可改变一个可变类:
class Outworld {
// This MAY be accessed by multiple threads
public static volatile MutableLong published;
}
// This class is mutable
class MutableLong {
private long value;
public MutableLong(long value) {
this.value = value;
}
public void increment() {
value++;
}
public long get() {
return value;
}
}
我们做到以下几点:
// Create a mutable object and modify it
MutableLong val = new MutableLong(1);
val.increment();
val.increment();
// No more modifications
// UPDATED: Let's say for this example we are completely sure
// that no one will ever call increment() since now
// Publish it safely and consider Effectively Immutable
Outworld.published = val;
的问题是: Java内存模型是否保证所有线程都必须有Outworld.published.get() == 3
?
根据Java Concurrency In Practice这应该是真的,但请纠正我,如果我错了。
3.5.3。安全出版习惯
要安全地发布对象,对象的引用和对象的状态必须同时对其他线程可见。 正确构造的对象可以通过以下方式安全地发布:
- 从静态初始化程序初始化对象引用;
- 将引用存储到易失性字段或AtomicReference中;
- 将引用存储到正确构造的对象的最终字段中;或
- 将对其的引用存储到由锁正确保护的字段中。3.5.4。有效不可变的对象
安全地发布有效的不可变对象可以安全地使用任何线程,而无需额外的同步。
请显示建立对象状态的[* static initializer *](http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html),该对象的状态是可见的。 – trashgod 2012-04-20 23:07:09