使用volatile而不同步 [英] Uses of volatile without synchronization
问题描述
知道
读取和写入是 atomic
问题1:这可以理解为
private volatile int x = 0;
x ++;
操作是原子的?
那
标记变量volatile并不能消除所有需要同步
原子操作,因为仍然可以内存一致性错误。 / p>
Marking variable volatile does not eliminate all need to synchronize atomic actions, because memory consistency errors are still possible.
问题2:我想知道在什么情况下(如果有的话)可以看到标记为<$的变量c $ c> volatile 并且看不到标记为同步的块的任何方法(试图访问/修改变量)?
Question2: I wonder under what circumstances (if any) it is possible to see a variable marked volatile
and not see any methods of blocks marked synchronized (that attempt to access/ modify the variable)?
换句话说,如果所有需要保护免于并发修改的变量都标记为 volatile
?
In other words, should all variables that need to be protected from concurrent modification be marked volatile
?
推荐答案
volatile只为你提供额外的可见性保证,长/双的原子写/读(否则JLS无法保证,是的)和一些内存顺序保证。 没有同步(虽然可以构建以volatile为开头的同步块,但是可以实现 - Dekker的算法)
所以不,它对 x ++
没有帮助 - 这仍然是一个读取,包含和写入,需要某种形式的同步。
The volatile only gives you additional visibility guarantees, atomic writes/reads for longs/doubles (otherwise not guaranteed by the JLS, yes) and some memory order guarantees. No synchronization (it is possible though to build synchronization blocks starting with just volatile - Dekker's algorithm )
So no, it does not help you with x++
- that's still a read, inc and write and needs some form of synchronization.
volatile的一个例子是着名的双重检查锁定,我们大部分时间都避免同步,因为排序保证是我们所需要的:
One example of volatile is the famous double-checked locking, where we avoid synchronization most of the time because the ordering guarantees are all we need:
private volatile Helper helper = null;
public Helper getHelper() {
if (helper == null) {
synchronized(this) {
if (helper == null) {
helper = new Helper();
}
}
}
return helper;
}
一个完全没有涉及同步的例子,是一个简单的退出标志,这里它不是关于订购保证而是关于保证的可见性
An example where there's absolutely no synchronization involved, is a simple exit flag, here it's not about ordering guarantees but only about the guaranteed visibility
public volatile boolean exit = false;
public void run() {
while (!exit) doStuff();
// exit when exit set to true
}
如果另一个线程设置 exit = true
执行while循环的其他线程可以保证看到更新 - 没有volatile,它可能不会。
If another thread sets exit = true
the other thread doing the while loop is guaranteed to see the update - without volatile it may not.
这篇关于使用volatile而不同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!