Sharing numeric values across threads using Java 8 LongAdder
October 8, 2016 Leave a comment
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.