挥发性实际上是如何工作的?

发布于 2024-08-30 15:02:03 字数 98 浏览 6 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

听风吹 2024-09-06 15:02:03

据我了解,它总是看起来好像缓存在写入后已被刷新,并且总是看起来好像在读取时直接从内存中进行读取。其效果是,一个线程将始终看到另一个线程的写入结果,并且(根据 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/

沉默的熊 2024-09-06 15:02:03

到底发生什么是特定于处理器的。通常存在某种形式的内存屏障指令。刷新整个缓存显然会非常昂贵 - 硬件中有缓存一致性协议。

同样重要的是,某些优化并未跨现场访问进行。在考虑多线程时编译器很重要,不要只考虑硬件。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文