JSR-133 FAQ说:
But there is more to synchronization
than mutual exclusion. Synchronization
ensures that memory writes by a thread
before or during a synchronized block
are made visible in a predictable
manner to other threads which
synchronize on the same monitor. After
we exit a synchronized block, we
release the monitor, which has the
effect of flushing the cache to main
memory, so that writes made by this
thread can be visible to other
threads. Before we can enter a
synchronized block, we acquire the
monitor, which has the effect of
invalidating the local processor cache
so that variables will be reloaded
from main memory. We will then be able
to see all of the writes made visible
by the previous release.
我还记得在现代Sun VM上阅读,无争议的同步是便宜的。我有点困惑的这个说法。考虑如下代码:
class Foo {
int x = 1;
int y = 1;
..
synchronized (aLock) {
x = x + 1;
}
}
对x的更新需要同步,但是锁的获取是否从高速缓存清除y的值?我不能想象是这样的情况,因为如果它是真的,像锁条纹的技术可能没有帮助。或者,JVM可以可靠地分析代码,以确保y不会在使用相同锁定的另一个同步块中修改,因此在进入同步块时不会转储缓存中y的值?