任何人都可以解释为什么这个例子是线程安全的没有易失性?线程安全无易失性
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
事实上,假设computeHashCode函数总是返回相同的结果,并且没有副作用(即幂等),你甚至可以摆脱所有同步的。
// Lazy initialization 32-bit primitives
// Thread-safe if computeHashCode is idempotent
class Foo {
private int cachedHashCode = 0;
public int hashCode() {
int h = cachedHashCode;
if (h == 0) {
h = computeHashCode();
cachedHashCode = h;
}
return h;
}
// other functions and members...
}
更多:我明白了,如果这个值被计算两次(所以它不是真正的线程安全),我们不关心。我也想知道在哈希码计算后创建的新线程是否可以保证看到新的哈希码?
也许你会考虑如果不使用synchronized或volatile会发生什么会更有用,你会明白为什么不需要它。 – 2012-02-01 22:02:32
请注意,“Foo”实际上是不可变的,这一点很重要。这保证'hashCode()'是幂等的。 – Kevin 2016-02-17 19:28:48