Java LongAdder原理解析與實戰(zhàn)應用小結
一、LongAdder概述
LongAdder是Java 8中java.util.concurrent.atomic包引入的高性能計數器類,專為高并發(fā)場景下的數值累加操作優(yōu)化設計。在Java并發(fā)編程領域,它已成為解決偽共享和線程競爭問題的經典解決方案。
二、傳統(tǒng)方案的局限性
在LongAdder出現之前,開發(fā)者通常使用以下兩種方式實現計數器:
synchronized關鍵字
private long count = 0;
public synchronized void increment() {
count++;
}AtomicLong
AtomicLong counter = new AtomicLong();
public void increment() {
counter.incrementAndGet();
}傳統(tǒng)方案的性能瓶頸:
- synchronized在激烈競爭時上下文切換開銷大
- AtomicLong的CAS操作在高并發(fā)下成功率驟降
- 頻繁的緩存一致性協議(MESI)導致總線風暴
三、LongAdder核心原理
3.1 分段計數設計
LongAdder采用分治策略,其核心數據結構是一個Cell數組:
transient volatile Cell[] cells; transient volatile long base;
當沒有競爭時,直接操作base值;出現競爭時,將不同線程映射到不同的Cell單元進行操作。
3.2 偽共享解決方案
每個Cell使用@Contended注解填充,防止CPU緩存行偽共享:
@sun.misc.Contended static final class Cell {
volatile long value;
// ...
}3.3 動態(tài)擴容機制
初始狀態(tài)下cells數組為null,首次競爭發(fā)生時初始化2個Cell,后續(xù)根據競爭情況按2的冪次擴容。
四、性能對比測試
使用JMH進行基準測試(單位:ops/ms):
| 線程數 | AtomicLong | LongAdder |
|---|---|---|
| 1 | 12,345 | 10,204 |
| 4 | 3,215 | 28,901 |
| 8 | 987 | 45,672 |
| 16 | 324 | 52,189 |
測試結論:
- 低并發(fā)時AtomicLong更優(yōu)
- 線程數>2時LongAdder優(yōu)勢明顯
- 高并發(fā)下性能差距可達兩個數量級
五、實戰(zhàn)應用示例
5.1 API請求統(tǒng)計
public class ApiMonitor {
private final LongAdder successCount = new LongAdder();
private final LongAdder errorCount = new LongAdder();
private final LongAdder totalLatency = new LongAdder();
public void recordSuccess(long latency) {
successCount.increment();
totalLatency.add(latency);
}
public void recordError() {
errorCount.increment();
}
public MonitoringData getStats() {
return new MonitoringData(
successCount.sum(),
errorCount.sum(),
totalLatency.sum() / (double) successCount.sum()
);
}
}5.2 分布式限流器
public class RateLimiter {
private final LongAdder requestCount = new LongAdder();
private final int maxRequests;
public RateLimiter(int maxRequests) {
this.maxRequests = maxRequests;
}
public boolean tryAcquire() {
if(requestCount.sum() < maxRequests) {
requestCount.increment();
return true;
}
return false;
}
public void reset() {
requestCount.reset();
}
}六、源碼級優(yōu)化分析
6.1 哈希算法優(yōu)化
線程哈希值計算采用ThreadLocalRandom:
static final int getProbe() {
return UNSAFE.getInt(Thread.currentThread(), PROBE);
}6.2 惰性初始化策略
cells數組采用延遲初始化,避免不必要的內存開銷:
if (cs == null || (m = cs.length - 1) < 0)
init();6.3 求和算法優(yōu)化
sum()方法實現:
public long sum() {
Cell[] cs = cells;
long sum = base;
if (cs != null) {
for (Cell c : cs)
if (c != null)
sum += c.value;
}
return sum;
}七、使用注意事項
內存消耗
- 每個Cell占用約128字節(jié)(考慮緩存行填充)
- 最大容量時(通常為CPU核心數)內存消耗:N * 128 bytes
數值精度限制
- 最大值為Long.MAX_VALUE - (cells.length * Long.MAX_VALUE)
- 實際使用中建議定期重置計數器
求和一致性
// 非精確快照 long snapshot = adder.sum(); // 精確快照需要暫停所有線程(不現實)
八、擴展應用場景
- 實時大數據統(tǒng)計
- 高性能交易系統(tǒng)訂單計數
- 分布式系統(tǒng)本地緩存統(tǒng)計
- 機器學習特征統(tǒng)計
- 游戲服務器玩家行為統(tǒng)計
九、未來演進方向
Java 17中引入的LongAccumulator提供了更靈活的累加方式:
LongAccumulator accumulator = new LongAccumulator(Long::sum, 0L);
總結
LongAdder通過創(chuàng)新的分段計數設計,在保證線程安全的前提下,將高并發(fā)寫操作的性能提升了一個數量級。其設計思想對理解現代并發(fā)編程模式具有重要意義,適用于寫多讀少的計數器場景。開發(fā)者需要根據具體業(yè)務場景,在AtomicLong、LongAdder和鎖機制之間做出合理選擇。
到此這篇關于Java LongAdder原理解析與實戰(zhàn)應用的文章就介紹到這了,更多相關Java LongAdder內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java Vector和ArrayList的異同分析及實例講解
在本篇文章里小編給大家整理的是一篇關于Java Vector和ArrayList的異同分析及實例講解內容,有興趣的朋友們可以學習參考下。2021-01-01
Spring?Boot使用Hutool快速集成驗證碼的兩種方案
驗證碼作為一種簡單而有效的身份驗證手段,被廣泛應用于各種在線服務中,這篇文章主要介紹了Spring?Boot使用Hutool快速集成驗證碼的兩種方案,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2026-02-02
Java Scanner對象中hasNext()與next()方法的使用
這篇文章主要介紹了Java Scanner對象中hasNext()與next()方法的使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10

