gpt4 book ai didi

java 8 : Are LongAdder and LongAccumulator preferred to AtomicLong?

转载 作者:搜寻专家 更新时间:2023-11-01 01:41:22 25 4
gpt4 key购买 nike

LongAdder 作为 AtomicLong

的替代品
ExecutorService executor = Executors.newFixedThreadPool(2);    
IntStream.range(0, 1000)
.forEach(i -> executor.submit(adder::increment));
stop(executor);
System.out.println(adder.sumThenReset()); // => 1000

LongAccumulatorLongAdder

的更通用版本
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

我有一些疑问。

  1. LongAdder 总是优先于 AtomicLong 吗?
  2. LongAccumulator 是否优于 LongAdder 和 AtomicLong?

最佳答案

Javadoc 中提到了这些类之间的区别,以及何时使用一个而不是另一个。来自 LongAdder :

This class is usually preferable to AtomicLong when multiple threads update a common sum that is used for purposes such as collecting statistics, not for fine-grained synchronization control. Under low update contention, the two classes have similar characteristics. But under high contention, expected throughput of this class is significantly higher, at the expense of higher space consumption.

来自LongAccumulator :

This class is usually preferable to AtomicLong when multiple threads update a common value that is used for purposes such as collecting statistics, not for fine-grained synchronization control. Under low update contention, the two classes have similar characteristics. But under high contention, expected throughput of this class is significantly higher, at the expense of higher space consumption.

[...]

Class LongAdder provides analogs of the functionality of this class for the common special case of maintaining counts and sums. The call new LongAdder() is equivalent to new LongAccumulator((x, y) -> x + y, 0L).

因此,使用其中一个取决于您的应用程序打算做什么。它并不总是严格首选,只有在期望高并发并且您需要维护公共(public)状态时才使用。

关于java 8 : Are LongAdder and LongAccumulator preferred to AtomicLong?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35688862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com