关于volatile的一点疑问

面试题关于volatile的一点疑问
liuchang6152 Staff asked 7 months ago

最近读 java关键字volatile。 知道它能保证可见性。如果变量用它修饰,则每次更新都会马上更新到主内存,
接下来就有疑问了
读一些不同的博客,有的说它更新到主内存时,马上刷新各个线程缓存,刷新成主内存最新数据,比如这个最后几句

而有的博文说,更新到主内存后,只是通知各个线程的缓存失效,而要等到各个线程读取主内存时才知道最新的值。比如这个

到底是刷新各个缓存还是只是使各个缓存数据失效啊?

原创文章,转载请注明: 转载自并发编程网 – ifeve.com本文链接地址: 关于volatile的一点疑问

FavoriteLoading添加本文到我的收藏
1 Answers
nathanielwen Staff answered 4 months ago

这个问题在JSR133 cookbook中有描述:http://g.oswego.edu/dl/jmm/cookbook.html
参考Categories中的例子:在volatile变量的写之后和读之间会插入一个内存屏障StoreLoad,这个指令的含义是:

ensures that Store1’s data are made visible to other processors (i.e., flushed to main memory) before data accessed by Load2 and all subsequent load instructions are loaded. StoreLoad barriers protect against a subsequent load incorrectly using Store1’s data value rather than that from a more recent store to the same location performed by a different processor. Because of this, on the processors discussed below, a StoreLoad is strictly necessary only for separating stores from subsequent loads of the same location(s) as were stored before the barrier. StoreLoad barriers are needed on nearly all recent multiprocessors, and are usually the most expensive kind. Part of the reason they are expensive is that they must disable mechanisms that ordinarily bypass cache to satisfy loads from write-buffers. This might be implemented by letting the buffer fully flush, among other possible stalls.

不过从你的截图来看,其实两段话在写操作时指的应该都是刷新到main memory,并且在读取数据时从main memory读取。

原创文章,转载请注明: 转载自并发编程网 – ifeve.com本文链接地址: Answer for 关于volatile的一点疑问

FavoriteLoading添加本文到我的收藏

return top