Odi's astoundingly incomplete notes
New entries | CodeJDK-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.
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)); }
Add comment