内存可见性是否取决于使用的监视器?锁释放B
后获取锁A
,内存可见性够吗?
例如以下代码:
int state; // shared
// thread A
synchronized (A) {
state += 1;
}
Thread.sleep(10000000);
// thread B
Thread.sleep(1000);
synchronized(B) {
state += 1;
}
线程在同一时间启动,线程B
休眠时间可以任意高,只是为了确保它在线程A
使用state
变量之后执行。线程A
睡眠时间用于确保线程在线程B
使用state
共享变量之前不会完成。
更新
来自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.
似乎本地内存刷新的过程并不像第一条语句中描述的那么简单,并且可能不会在每次锁定释放时发生?