2

メモリの可視性は、使用するモニターによって異なりますか? ロックが解放されBた後にロックが取得されますAが、メモリの可視性には十分ですか?

たとえば、次のコード:

int state; // shared


// thread A
synchronized (A) {
 state += 1;
}
Thread.sleep(10000000);

// thread B
Thread.sleep(1000);
synchronized(B) {
 state += 1;
}

スレッドは同時に開始され、スレッドのスリープ時間は、スレッドが変数を使用Bした後に確実に実行されるように、任意に長くすることができます。スレッドのスリープ時間は、スレッドが共有変数を使用する前にスレッドが終了しないようにするために使用されます。AstateABstate

アップデート

http://www.ibm.com/developerworks/library/j-jtp03304/から

When a thread exits a synchronized block as part of releasing the associated monitor, the JMM requires that the local processor cache be flushed to main memory.

Similarly, as part of acquiring the monitor when entering a synchronized block, local caches are invalidated so that subsequent reads will go directly to main memory and not the local cache.

stateこれが真の場合、変数がスレッドに表示されない理由はわかりませんB

さらに、彼らはモニターが同じであるべきだと言っていますが、それは前述の声明から暗示されているわけではありません.

This process guarantees that when a variable is written by one thread during a synchronized block protected by a given monitor and read by another thread during a synchronized block protected by the same monitor, the write to the variable will be visible by the reading thread. 

ローカル メモリ フラッシュのプロセスは、最初のステートメントで説明されているように単純ではなく、すべてのロック リリースで発生するとは限らないようです。

4

2 に答える 2