LongAdder和AtomicLong性能对比
jdk1.8中新原子操作封装类LongAdder和jdk1.5的AtomicLong和synchronized的性能对比,直接上代码:
package com.itbac.cas; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.LongAdder; // 测试用例: 同时运行2秒,检查谁的次数最多 public class LongAdderDemo { // synchronized 方式 private long count = 0; // Atomic方式 private AtomicLong acount = new AtomicLong(0L); // LongAdder 方式 (jdk1.8,新计数器) private LongAdder lacount = new LongAdder(); // 运行时间,毫秒数 private int time=2000; // 同步代码块的方式 public void testSync() throws InterruptedException { for (int i = 0; i < 3; i++) { new Thread(() -> { long starttime = System.currentTimeMillis(); while (System.currentTimeMillis() - starttime < time) { // 运行两秒 synchronized (this) { ++count; } } long endtime = System.currentTimeMillis(); System.out.println("SyncThread spend:" + (endtime - starttime) + "ms" + " v:" + count); }).start(); } } public void testAtomic() throws InterruptedException { for (int i = 0; i < 3; i++) { new Thread(() -> { long starttime = System.currentTimeMillis(); while (System.currentTimeMillis() - starttime < time) { // 运行两秒 acount.incrementAndGet(); // acount++; } long endtime = System.currentTimeMillis(); System.out.println("AtomicThread spend:" + (endtime - starttime) + "ms" + " v:" + acount.incrementAndGet()); }).start(); } } public void testLongAdder() throws InterruptedException { for (int i = 0; i < 3; i++) { new Thread(() -> { long starttime = System.currentTimeMillis(); while (System.currentTimeMillis() - starttime < time) { // 运行两秒 lacount.increment(); } long endtime = System.currentTimeMillis(); System.out.println("LongAdderThread spend:" + (endtime - starttime) + "ms" + " v:" + lacount.sum()); }).start(); } } public static void main(String[] args) throws InterruptedException { LongAdderDemo demo = new LongAdderDemo(); demo.testSync(); demo.testAtomic(); demo.testLongAdder(); } }
看看输出结果:
SyncThread spend:2000ms v:25458554 SyncThread spend:2000ms v:25458554 SyncThread spend:2000ms v:25458554 AtomicThread spend:2000ms v:78489760 AtomicThread spend:2000ms v:78489759 AtomicThread spend:2000ms v:78489758 LongAdderThread spend:2000ms v:141154988 LongAdderThread spend:2000ms v:141154988 LongAdderThread spend:2000ms v:141352859
jdk版本,作者及类名:
* @since 1.5
* @author Doug Lea
AtomicLong
* @since 1.8
* @author Doug Lea
LongAdder
让我们来膜拜一下大神!2秒破亿次累加。翻倍的性能提升。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?