加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java 8:LongAdder和LongAccumulator是AtomicLong的首选吗?

发布时间:2020-12-15 04:32:40 所属栏目:Java 来源:网络整理
导读: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 LongAc
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

LongAccumulator是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

我有一些疑问.

> LongAdder总是优先于AtomicLong吗?
> 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,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).

因此,一个使用另一个取决于您的应用程序打算做什么.它并不总是严格优先,只有在预期高并发并且您需要维持一个共同状态时.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读