2

Could you please help me to grasp the gist of some methods of AtomicInteger class: updateAndGet, accumulateAndGet.

Why the first one recieves IntUnaryOperator as a parameter? What logic can potentially be applied in functional method of this interface? My thoughts, it would be easier to recieve just plain int value. (Same with IntBinaryOperator interface).

Thanks in advance.

void
  • 731
  • 2
  • 11
  • 26

1 Answers1

7

If you wanted to atomically double the value stored in an AtomicInteger, the best you could do before Java 8 was write

while (true) {
  int x = ai.get();
  if (ai.compareAndSet(x, 2 * x)) {
    return 2 * x;
  }
}

...but Java 8 lets you write e.g.

ai.updateAndGet(x -> 2 * x);

...and accumulateAndGet would, say, let you atomically multiply ai by y with

ai.accumulateAndGet(y, (x, y) -> x * y);

...which can also be implemented with updateAndGet but may be simpler to use in some cases where you already have a two-argument operation.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413