以下に簡単な例を示します。
private long counter = 0;
// note this method is NOT synchronized
// this will be called by thread A
public void increment() { counter++; }
// note this method IS synchronized
// this will be called by thread B
public synchronized long value() { return counter; }
counter
したがって、変数は不揮発性であるため、CPUキャッシュにスタックされた値ではなく、の適切な値を取得したいだけです。目標は、カウンターを揮発性にしないことです。そのため、インクリメントを行うスレッド A には影響しませんが、変数を読み取るときに気にしないスレッド B のみに影響します。
記録のために、counter
スレッド A がとにかく終了したときに、スレッド B から の値を読み取る予定です...