atomics package summary 末尾有注释指出:
... You can also hold
floats
usingFloat.floatToIntBits
andFloat.intBitstoFloat
conversions, anddoubles
usingDouble.doubleToLongBits
andDouble.longBitsToDouble
conversions.
显然,您不能将这些值简单地加在一起,所以什么相当于 double
值的原子 addAndGet
。
private AtomicLong sum = new AtomicLong();
...
// This would almost certainly NOT work.
public long add(double n) {
return sum.addAndGet(Double.doubleToLongBits(n));
}
你可以假设我非常努力地不使用synchronized
。
最佳答案
Guava 提供 AtomicDouble
,并且使用它可能是最简单的事情,而不是自己滚动......
就是说,它在内部是用AtomicLong
的包装器实现的,你可以看到他们对addAndGet
的实现here ;基本上是
while (true) {
long current = value;
double currentVal = longBitsToDouble(current);
double nextVal = currentVal + delta;
long next = doubleToRawLongBits(nextVal);
if (updater.compareAndSet(this, current, next)) {
return nextVal;
}
}
这确实是不处理汇编的唯一方法。
完全披露:我在 Guava 工作。
关于java - 添加原子 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9874676/