挥发性实际上是如何工作的?
在 Java 中将变量标记为 易失性 可以确保每个线程看到最后写入该变量的值,而不是某个过时的值。我想知道这是如何实现的。 JVM 是否会发出刷新 CPU 缓存或其他内容的特殊指令?
Marking a variable as volatile
in Java ensures that every thread sees the value that was last written to it instead of some stale value. I was wondering how this is actually achieved. Does the JVM emit special instructions that flush the CPU cashes or something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我了解,它总是看起来好像缓存在写入后已被刷新,并且总是看起来好像在读取时直接从内存中进行读取。其效果是,一个线程将始终看到另一个线程的写入结果,并且(根据 Java 内存模型)永远看不到缓存的值。然而,实际的实现和 CPU 指令会因架构而异。
如果您在多个线程中递增变量,或者检查其值并采取某些操作,则它不能保证正确性,因为显然没有实际的同步。通常,只有只有线程写入变量而其他线程都在读取时,才能保证正确执行。
另请注意,64 位非易失性变量可以作为两个 32 位变量进行读/写,因此 32 位变量在写入时是原子的,但 64 位变量则不是。一半可以在另一半之前写入 - 因此读取的值既可以是旧值也可以是新值。
这是我书签中非常有用的页面:
http://www.cs.umd .edu/~pugh/java/memoryModel/
From what I understand it always appears as if the cache has been flushed after write, and always appears as if reads are conducted straight from memory on read. The effect is that a Thread will always see the results of writes from another Thread and (according to the Java Memory Model) never a cached value. The actual implementation and CPU instructions will vary from one architecture to another however.
It doesn't guarantee correctness if you increment the variable in more than one thread, or check its value and take some action since obviously there is no actual synchronization. You can generally only guarantee correct execution if there is only just Thread writing to the variable and others are all reading.
Also note that a 64 bit NON-volatile variable can be read/written as two 32 bit variables, so the 32 bit variables are atomic on write but the 64 bit ones aren't. One half can be written before another - so the value read could be nether the old or the new value.
This is quite a helpful page from my bookmarks:
http://www.cs.umd.edu/~pugh/java/memoryModel/
到底发生什么是特定于处理器的。通常存在某种形式的内存屏障指令。刷新整个缓存显然会非常昂贵 - 硬件中有缓存一致性协议。
同样重要的是,某些优化并未跨现场访问进行。在考虑多线程时编译器很重要,不要只考虑硬件。
Exactly what happens is processor-specific. Generally there are some form of memory barrier instructions. Flushing the entire cache would obviously be very expensive - there are cache coherency protocols in the hardware.
Also important, is that certain optimisations are not made across the field accesses. The compiler is important when considering multithreading, don't just think about the hardware.