问题描述
我看到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引入了一个新的类看起来比AtomicInteger执行得更好。一些博客文章声称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?
推荐答案
是的,如果我正确理解您的声明。
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.
当要检索最终结果(sum)时, 。
When the final result (sum) is to be retrieved, it just adds together the values of each cell.
关于单元格是如何组织的,如何分配等等的很多逻辑可以在源代码中看到:
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更好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!