本文介绍了易失性变量“读取”和正常读取一样快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道写入 volatile 变量会将其从所有cpus的内存中刷新,但是我想知道对volatile变量的读取是否和正常一样快读?



可以将 volatile 变量置于cpu缓存中,还是总是从主内存中取出?

解决方案

你应该看看这篇文章:



感谢Marc Booker运行这些测试。


I know that writing to a volatile variable flushes it from the memory of all the cpus, however I want to know if reads to a volatile variable are as fast as normal reads?

Can volatile variables ever be placed in the cpu cache or is it always fetched from the main memory?

解决方案

You should really check out this article: http://brooker.co.za/blog/2012/09/10/volatile.html. The blog article argues volatile reads can be a lot slower (also for x86) than non-volatile reads on x86.

  • Test 1 is a parallel read and write to a non-volatile variable. Thereis no visibility mechanism and the results of the reads arepotentially stale.
  • Test 2 is a parallel read and write to a volatile variable. This does not address the OP's question specifically. However worth noting that a contended volatile can be very slow.
  • Test 3 is a read to a volatile in a tight loop. Demonstrated is that the semantics of what it means to be volatile indicate that the value can change with each loop iteration. Thus the JVM can not optimize the read and hoist it out of the loop. In Test 1, it is likely the value was read and stored once, thus there is no actual "read" occurring.

Credit to Marc Booker for running these tests.

这篇关于易失性变量“读取”和正常读取一样快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 12:20