LongAdder 的性能比 AtomicLong 好多少 [英] How LongAdder performs better than AtomicLong

查看:21
本文介绍了LongAdder 的性能比 AtomicLong 好多少的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了 Java 的 AtomicInteger 如何在内部与 CAS(比较和交换)操作一起工作.基本上当多个线程尝试更新值时,JVM 在内部使用底层 CAS 机制并尝试更新值.如果更新失败,则使用新值重试,但不要阻塞.

I see how Java's AtomicInteger works internally with CAS (Compare And Swap) operation. Basically when multiple threads try to update the value, JVM internally use the underlying CAS mechanism and try to update the value. If the update fails, then try again with the new value but never blocks.

在 Java8 中 Oracle 引入了一个新类 LongAdder 在高竞争下似乎比 AtomicInteger 表现更好.一些博客文章声称 LongAdder 通过维护内部单元格性能更好 - 这是否意味着 LongAdder 在内部聚合值并稍后更新它?你能帮我理解 LongAdder 的工作原理吗?

In Java8 Oracle introduced a new Class LongAdder which seems to perform better than AtomicInteger under high contention. Some blog posts claim that LongAdder perform better by maintaining internal cells - does that mean LongAdder aggregates the values internally and update it later? Could you please help me to understand how LongAdder works?

推荐答案

这是否意味着 LongAdder 在内部聚合这些值并稍后更新?

does that mean LongAdder aggregates the values internally and update it later?

是的,如果我理解正确的话.

Yes, if I understand your statement correctly.

LongAdder 中的每个 Cell 都是 AtomicLong 的变体.拥有多个这样的单元是分散争用并因此增加吞吐量的一种方式.

Each Cell in a LongAdder is a variant of an AtomicLong. Having multiple such cells is a way of spreading out the contention and thus increasing throughput.

当要检索最终结果(和)时,它只是将每个单元格的值相加.

When the final result (sum) is to be retrieved, it just adds together the values of each cell.

关于单元格如何组织、如何分配等的大部分逻辑都可以在源中看到:http://hg.openjdk.java.net/jdk9/jdk9/jdk/file/f398670f3da7/src/java.base/share/classes/java/util/concurrent/atomic/Striped64.java

Much of the logic around how the cells are organized, how they are allocated etc can be seen in the source: http://hg.openjdk.java.net/jdk9/jdk9/jdk/file/f398670f3da7/src/java.base/share/classes/java/util/concurrent/atomic/Striped64.java

特别是单元的数量受 CPU 数量的限制:

In particular the number of cells is bound by the number of CPUs:

/** Number of CPUS, to place bound on table size */
static final int NCPU = Runtime.getRuntime().availableProcessors();

这篇关于LongAdder 的性能比 AtomicLong 好多少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆