任何人都可以解釋爲什麼這個例子是線程安全的沒有易失性?線程安全無易失性
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