[1666774 views]

[]

Odi's astoundingly incomplete notes

New entries | Code

JDK-1.8 simplifies atomic maximizer

With Java 8 the atomic primitives have gained a very useful function: getAndUpdate(). It takes a lamda function to atomically update the value. This simplifies previous complicated code that used compareAndSet in a loop into a one-liner.

As an example look at a piece of code that is used to keep track of a maximum value.
private AtomicInteger max = new AtomicInteger();

public void oldSample(int v) {
  int old;
  do {
      old = c.get();
  } while (!c.compareAndSet(old, Math.max(old, v)));
}

public void newSample(int v) {
  max.getAndUpdate(old -> Math.max(old, v));
}

posted on 2019-05-21 09:45 UTC in Code | 0 comments | permalink