Add atomic twins
There is a note at the end of the brief description of the atomization package:
... You can also navigate
floats
using the transformationsFloat.floatToIntBits
andFloat.intBitstoFloat
anddoubles
using the transformationsDouble.doubleToLongBits
andDouble.longBitsToDouble
.
Obviously, you cannot just add these values together in a way that is equivalent to atomic addAndGet
for the value double
.
private AtomicLong sum = new AtomicLong();
...
// This would almost certainly NOT work.
public long add(double n) {
return sum.addAndGet(Double.doubleToLongBits(n));
}
It can be assumed that I am trying very hard NOT to use synchronized
.
source to share
Guava provides AtomicDouble
, and using this is probably the easiest thing to do, not rolling it yourself ...
However, it is internally implemented with a wrapper around it AtomicLong
, you can see their implementation addAndGet
here ; it's mostly
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;
}
}
which is really the only way to do it without having to deal with the assembly.
Full disclosure: I'm working on Guava.
source to share