gpt4 book ai didi

java - 获取锁时的内存可见性

转载 作者:行者123 更新时间:2023-11-30 07:16:10 25 4
gpt4 key购买 nike

内存可见性是否取决于所使用的监视器?释放锁A后获取锁B,内存可见性是否足够?

例如下面的代码:

int state; // shared


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

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

线程同时启动,线程B hibernate 时间可以任意长,只是为了确保在线程A使用state<之后执行变量。线程 A hibernate 时间用于确保线程不会在线程 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 不可见

此外,尽管他们说 monitor 应该相同,但上述声明并未暗示这一点。

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. 

似乎本地内存刷新的过程并不像第一条语句中描述的那么简单,并且可能不会在每次 锁释放时发生?

最佳答案

是的,这取决于。你可以阅读这个doc对这个。相关部分是“17.4.4.同步顺序”:

An unlock action on monitor m synchronizes-with all subsequent lock actions on m (where "subsequent" is defined according to the synchronization order).

你看,那里指定了一个具体的监控对象m。如果监视器不同,则您不会获得同步关系,因此,您不会获得先行发生关系(从 17.4.5 开始):

If an action x synchronizes-with a following action y, then we also have hb(x, y).

因此,您的更新将乱序执行,可能会丢失更新。

关于java - 获取锁时的内存可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17255985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com