Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add atomic doubles

There is a note at the end of the atomics package summary that states:

... You can also hold floats using Float.floatToIntBits and Float.intBitstoFloat conversions, and doubles using Double.doubleToLongBits and Double.longBitsToDouble conversions.

Obviously you cannot just add these values together so what would be the equivalent to the atomic addAndGet for a double value.

private AtomicLong sum = new AtomicLong();
...
// This would almost certainly NOT work.
public long add(double n) {
  return sum.addAndGet(Double.doubleToLongBits(n));
}

You can assume I am trying very hard NOT to use synchronized.

like image 566
OldCurmudgeon Avatar asked Nov 05 '25 12:11

OldCurmudgeon


1 Answers

Guava provides AtomicDouble, and using that is probably the simplest thing to do, rather than rolling it yourself...

That said, it's internally implemented with a wrapper around AtomicLong, you can see their implementation of addAndGet here; it's basically

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 dealing with assembly.

Full disclosure: I work on Guava.

like image 166
Louis Wasserman Avatar answered Nov 08 '25 10:11

Louis Wasserman