我想知道打电话是否有什么区别(或可能的副作用):
AtomicBoolean.set(true)和
AtomicBoolean.compareAndset(false, true)JavaDoc of AtomicBoolean#set声明:
无条件地设置给定的值。
而AtomicBoolean#compareAndSet声明:
如果当前值==为期望值,则原子地将值设置为给定的更新值。
在这两种情况下,该值都将设置为true。那有什么区别呢?
发布于 2012-11-13 15:41:32
如果值已经是compareAndset(false, true),则false将返回true。
它实际上相当于!getAndSet(true)。
发布于 2012-11-13 15:45:23
您引用的文本明确地说明了这两个操作之间的区别。但是,为了更清楚地说明,如果忽略原子性方面,第一个方面相当于:
public void set(boolean newValue) {
this.value = newValue;
}第二项相当于:
public boolean compareAndSet(boolean expected, boolean newValue) {
if (this.value == expected) {
this.value = newValue;
return true;
} else {
return false;
}
}对于您的示例,set(true)将状态设置为true,compareAndset(false, true)将状态设置为true当且仅当它不是true。因此,是的,对AtomicBoolean状态的净影响是相同的。
但是,您会注意到,根据return对象的初始状态,AtomicBoolean值不同.因此,从这个角度来看,方法是不等价的,即使是那些参数值。
发布于 2015-02-26 07:42:10
降落在这里,从性能的角度寻找答案。由于不确定本机实现与决策块之间的关系,我最终编写了代码来对其进行评估。根据结果,set()肯定占据了性能的上风,因为它不需要经过多个决策块。请查找下面的代码和输出。
public static void main(String[] args) {
boolean curValue = true;
boolean dummyValue = true;
int attempts = Integer.MAX_VALUE;
AtomicBoolean test = new AtomicBoolean(curValue);
long start = System.currentTimeMillis();
for(int i=0; i<attempts; i++){
test.set(true);
dummyValue = !dummyValue;
}
System.out.println("time taken for set: "+(System.currentTimeMillis()-start));
start = System.currentTimeMillis();
for(int i=0; i<attempts; i++){
test.compareAndSet(curValue, curValue); // always set the same value
dummyValue = !dummyValue;
}
System.out.println("time taken for compareAndSet - same value case: "+(System.currentTimeMillis()-start));
curValue = !curValue;
start = System.currentTimeMillis();
for(int i=0; i<attempts; i++){
test.compareAndSet(curValue, !curValue); // always invert
curValue = !curValue;
}
System.out.println("time taken for compareAndSet - inversion case: "+(System.currentTimeMillis()-start));
}输出:
time taken for set: 2689
time taken for compareAndSet - same value case: 15559
time taken for compareAndSet - inversion case: 14802https://stackoverflow.com/questions/13363752
复制相似问题