volatile实际如何工作? [英] How does volatile actually work?

查看:204
本文介绍了volatile实际如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中将变量标记为 volatile 可确保每个线程都会看到上次写入的值,而不是某个过期值。我想知道这是如何实际实现。 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?

推荐答案

根据我的理解,在写入之后已经被刷新,并且总是看起来好像在读取时从存储器直接进行读取。效果是,线程将总是看到来自另一个线程的写入结果(根据Java内存模型)从不是一个缓存的值。但是,实际的实现和CPU指令在不同的架构中会有所不同。

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.

另外请注意,一个64位的非易失性变量可以被写入变量中,读/写为两个32位变量,因此32位变量在写入时是原子的,但64位变量不是。一半可以写在另一个之前 - 所以读取的值可能是旧的或新的值。

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/

这篇关于volatile实际如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆