Sharing numeric values across threads using Java 8 LongAdder

In this post we saw how to share primitive values across threads using the various atomic objects in the java.util.concurrent.atomic package. The example code demonstrated the AtomicInteger object which is the thread-safe variant of a “normal” integer. Mathematical operations like adding a value to an integer are carried out atomically for that object. This means that the low-level instructions involved in adding two integers are carried out as one unit without the risk of another interfering thread. The same package includes atomic versions of other primitive values such as AtomicBoolean or AtomicLong.

In this post we’ll take a quick look at an addition in Java 8 relevant to sharing integers, longs and doubles.

The java.util.concurrent.atomic package includes the LongAdder and DoubleAdder classes in Java 8. They are better suited than their Atomic* counterparts in situations where a high number of threads try to update the same variable.

LongAdder has methods similar to those in AtomicInteger to increment, decrement or extract the current value. The sum() method returns the current value as a long and it’s equivalent to the longValue() method. There are other methods to convert the sum to floats and integers.

Here’s the code of the SharedPrimitiveTesterService class from the previous post: