Java 8 introduces lots of improvement like Stamped Locks Locks, Parallel Sorting Long or Double Adder and Long or Double Accumulator and lots of improvement.
LongAdder and LongAccumators they were present under java.util.concurrent.atomic.
LongAdder and LongAccumators which are recommended instead of the Atomic classes when multiple threads update frequently and less read frequently. During high contention, they were designed in such a way they can grow dynamically.
Atomic classes(AtomicLong or AtomicDouble) internally uses a volatile variable, so for any operation data need to fetch from memory which requires many CPU cycles, under heavy contention lot of CPU cycles has been wasted.
So LongAdder and LongAccumator design in such a way they use its local values for each thread and at last they can sum all the values. Internally they use cell object array which can grow on demand where the store value. More threads are calling increment(), the array will be longer. Each record in the array can be updated separately.
The code below shows how you can use LongAdder to calculate the sum of several values:
LongAdder counter = new
LongAdder();
ExecutorService service = Executors.newFixedThreadPools(4);
Runnable incrementTask = () -> {
counter.increment() ;
};
for
(int
i = 0; i < 4; i++) {
executorService.execute(incrementTask);
}
// get the current sum
long sum = counter.sum();
The result of the counter in the LongAdder is not available until we call the sum() method. This method iterates over the cell array and sums up all the value.
Adder class is used, to sum up, or adding the value, whereas Accumulator classes are given a commutative function to combine values or perform some action.
The code below shows how you can use LongAccumulator to calculate the sum of several values:
LongAccumulator acc = new
LongAccumulator(Long::sum, 0);
ExecutorService service = Executors.newFixedThreadPools(4);
Runnable incrementTask = () -> {
acc.
accumulate() ;
};
for
(int
i = 0; i < 4; i++) {
executorService.execute(incrementTask);
}
// get the current sum
long sum = acc.get();
Here we have passed the sum function of Long class accumulate function will call our sum to function.
These classes implementations are very clever implementations in java8 they save a lot of CPU cycles and increasing the overall speed of execution of the process
No comments:
Post a Comment