Java LongAdder

来自WHY42
Riguz讨论 | 贡献2023年12月19日 (二) 06:54的版本 (Riguz移动页面Java:LongAdderJava LongAdder,不留重定向)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

LongAdder跟AtomicLong功能类似,但是在高竞争的场景下表现更优。例如结合ConcurrentHashMap来维护一个频率列表:

ConcurrentHashMap<String,LongAdder> freqs; //...
freqs.computeIfAbsent(key, k -> new LongAdder()).increment();}

The implementation extends Striped64, which is a data holder for 64-bit values. The values are held in cells, which are padded (or striped), hence the name. Each operation made upon the LongAdder will modify the collection of values present in the Striped64. When contention occurs, a new cell is created and modified, so the the old thread can finish concurrently with contending one. When you need the final value, the sums of each cell is simply added up.