Java 8: are longadder and longaccumulator the first choice for atomiclong?
•
Java
Longadder as a substitute for atomiclong
ExecutorService executor = Executors.newFixedThreadPool(2); IntStream.range(0,1000) .forEach(i -> executor.submit(adder::increment)); stop(executor); System.out.println(adder.sumThenReset()); // => 1000
Longaccumulator is a more general version of longadder
LongBinaryOperator op = (x,y) -> 2 * x + y; LongAccumulator accumulator = new LongAccumulator(op,1L); ExecutorService executor = Executors.newFixedThreadPool(2); IntStream.range(0,10) .forEach(i -> executor.submit(() -> accumulator.accumulate(i))); stop(executor); System.out.println(accumulator.getThenReset()); // => 2539
I have some questions
>Does longadder always take precedence over atomiclong? > Is the longaccumulator the first choice for longadder and atomiclong?
Solution
Javadoc mentions the differences between these classes and when to use one of them Start with longadder:
Start with the longaccumulator:
Therefore, one uses the other depending on what your application is going to do It is not always strictly priority, only when high concurrency is expected and you need to maintain a common state
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码