AtomicLong详解(作用原理及9大用法)

AtomicLong详解(作用原理及9大用法)-mikechen

AtomicLong定义

AtomicLong 类位于java.util.concurrent.atomic 包中,是一个以原子方式操作Long值的类,与AtomicInteger非常类似,变量可以原子写和读。

 

AtomicLong作用

AtomicLong作用:保证了并发时线程安全的累加操作。

AtomicLong的原理:底层是使用CAS实现,比 Synchronized 开销更小,执行效率更高,在多线程环境下,无锁的进行原子操作。

 

创建AtomicLong

如下代码创建 AtomicLong :

AtomicLong atomicLong = new AtomicLong();

上述例子创建了初始值为0的AtomicLong ,如果需要创建指定值的AtomicLong ,则代码如下:

AtomicLong atomicLong = new AtomicLong(123);

例子中用123作为AtomicLong 构造函数的参数,意思就是AtomicLong 实例的初始值为123。

获取AtomicLong 的值

可以通过 AtomicLong 的 get() 方法获取值,下面是代码 AtomicLong .get():

AtomicLong atomicLong = new AtomicLong(123);
 
long theValue = atomicLong.get();

设置AtomicLong的值

可以通过 AtomicLong 的set()方法设置值,下面是 AtomicLong .set()的例子

AtomicLong atomicLong = new AtomicLong(123);
 
atomicLong.set(234);

例子中创建了一个初始值为123的 AtomicLong ,然后设置为234.

比较AtomicLong的值

AtomicLong 类同样有原子的compareAndSet()方法,首先与AtomicLong 实例值得当前比较,如果相对这设置AtomicLong 的新值,下面AtomicLong .compareAndSet()代码:

AtomicLong atomicLong = new AtomicLong(123);
 
long expectedValue = 123;
long newValue      = 234;
atomicLong.compareAndSet(expectedValue, newValue);

首先创建初始值为123的 AtomicLong 实例,然后当前值与期望值123比较,如果相对则设置值为234.

增加AtomicLong的值

AtomicLong 类包含了一些增加和获取返回值的方法:

  • addAndGet()
  • getAndAdd()
  • getAndIncrement()
  • incrementAndGet()

第一个方法 addAndGet() ,增加AtomicLong 的值同时返回增加后的值,第二个方法 getAndAdd()增加值,但是返回增加之前的值,两个方法的差别看下面代码:

AtomicLong atomicLong = new AtomicLong();
 
 
System.out.println(atomicLong.getAndAdd(10));
System.out.println(atomicLong.addAndGet(10));

代码例子将为0和20,首先获取AtomicLong 增加10之前的值是0,然后再增加值并获取当前值是 20.同样可以通过两个方法增加负值,相当于做减法,getAndIncrement()和 incrementAndGet() 与 getAndAdd()和 addAndGet()的工作原理相似,只不是加1.

AtomicLong减法

AtomicLong 类同样可以原子性的做减法,面是方法:

  • decrementAndGet()
  • getAndDecrement()

decrementAndGet()方法减1并返回减后的值,getAndDecrement()同样减1并返回减之前的值 。

 

AtomicLong应用场景

例如:我们某些应用需要生成序列号或唯一ID时,那么就可以用到AtomicLong。

作者简介

陈睿|mikechen,10年+大厂架构经验,BAT资深面试官,就职于阿里巴巴、淘宝、百度等一线互联网大厂。

👇阅读更多mikechen架构文章👇

阿里架构 |双11秒杀 |分布式架构 |负载均衡 |单点登录 |微服务 |云原生 |高并发 |架构师

以上

关注作者「mikechen」公众号,获取更多技术干货!

后台回复架构,即可获取《阿里架构师进阶专题全部合集》,后台回复面试即可获取《史上最全阿里Java面试题总结

评论交流
    说说你的看法