Java Reference
In-Depth Information
Adding 1
Adding 2
Adding 3
Adding 4
Adding 5
Adding 6
Adding 7
Adding 8
Adding 9
The sum is: 90.0
How It Works
Prior to the release of Java 8, it was important to utilize atomic numbers when working
with values across multiple threads. Atomic variables prevent thread interference
without causing obstruction in the way that synchronized access may cause in some
cases. Java 8 introduced a new line of atomic variables that provide for faster through-
put than standard atomic variables. The
java.util.concurrent.atomic.DoubleAdder
and
java.util.concurrent.atomic.LongAdder
classes are preferable to
AtomicDouble
and
AtomicLong
in most cases when the values may be accessed
and updated across multiple threads. Both
DoubleAdder
and
LongAdder
extend
Number
, and they are useful when summing values across threads, especially under
high contention.
In the solution, a
DoubleAdder
is used to sum numbers across two different
threads. Using the
add()
method, various numbers are “added” to the
DoubleAd-
der
value. After the threads have had ample time to perform their work, the
doubleValue()
method is called upon to return the sum of all values as a double.
Both the
DoubleAdder
and
LongAdder
classes contain similar methods, al-
though the
LongAdder
does contain a couple of additional helper methods for incre-
are contained within each of the classes.
Table 10-2
.
DoubleAdder and LongAdder Methods
Method
Description
Adds the given value.
add()