线标题应该是自我解释的.我对AtomicBoolean类中的以下方法的规范有些困惑:
java.util.concurrent.atomic.AtomicBoolean#compareAndSetjava.util.concurrent.atomic.AtomicBoolean#getAndSet我的分析是,当作为if条件中的布尔子句使用时,两者都会导致相同的行为:
public class Test {
private AtomicBoolean flag = AtomicBoolean(false);
public void processSomeAction() {
if (flag.getAndSet(false)) { // Shouldn't this be similar to flag.compareAndSet(false)
// process some action
}
}
//...
private void internalMutatorMethod() {
// do some staff then update the atomic flag
flas.set(true);
}
}假设我想检索当前的标志值并自动更新它,那么这两个方法不应该产生相同的行为吗?
如果我忽略了内部的差异,我将非常感激任何关于如何和何时使用这些方法的解释。
发布于 2015-01-26 09:44:17
documentation非常清楚。
getAndSet ->“原子地将给定值设置为并返回前一个值.”compareAndSet ->“如果当前值==为期望值,则原子地将值设置为给定的更新值。不足为奇的是,compareAndSet采用了两个参数。
就你的具体情况而言:
if (flag.getAndSet(false))时,flag才会设置为false。if (flag.compareAndSet(true, false))发布于 2015-01-26 09:47:12
您可以查看代码以更好地理解:
public final boolean getAndSet(boolean newValue) {
for (;;) {
boolean current = get();
if (compareAndSet(current, newValue))
return current;
}
}在getAndSet中,如果布尔值的值在您更改旧值的时间和试图更改其值的时间之间发生了变化,则compareAndSet不会更改其值。因此,getAndSet在循环中调用compareAndSet,直到布尔值设置为新值为止。
关于您的代码示例:
flag.getAndSet(false)返回AtomicBoolean的旧值。另一方面,flag.compareAndSet(x,false) (注意有两个参数)返回AtomicBoolean是否被修改,或者换句话说,它返回AtomicBoolean的旧值是否为x。
发布于 2015-01-26 09:46:51
当我检查了实现后,我发现
public final boolean getAndSet(boolean newValue) {
for (;;) {
boolean current = get();
if (compareAndSet(current, newValue))
return current;
}
}另外,在检查javadoc时,compareAndSet只在比较通过时设置值,而getAndSet只设置值并返回前一个值。
https://stackoverflow.com/questions/28147654
复制相似问题