AtomicLong al = new AtomicLong(); AtomicLong al = new AtomicLong(0L);
无参构造,相当于AutomicLong(0L)
有参构造,初始化为initValue
AtomicLong al = new AtomicLong(); System.out.println(al.getAndIncrement()); // 先返回0,再自增 System.out.println(al.incrementAndGet()); // 先自增,后返回2
类比AtomicInteger:
getAndIncrement先返回现值,后自增1
incrementAndGet先自增1,后返回值
AtomicLong al = new AtomicLong(5L); System.out.println(al.getAndDecrement()); // 先返回5,再自减 System.out.println(al.decrementAndGet()); // 先自减,后返回3
类比AtomicInteger:
getAndDecrement先返回现值,后自减1
decrementAndGet先自减1,后返回值
public boolean compareAndSet(long source, long dest):source是改之前的值,Dest是改之后的值,source与当前真实值匹配了才能执行成功,返回值表示是否执行成功。
AtomicLong al = new AtomicLong(5L); System.out.println(al.compareAndSet(4L, 6L)); // 如果原值为4,更新成6, false System.out.println(al.get()); // 5 System.out.println(al.compareAndSet(5L, 7L)); // 如果原值为5,更新成7, true System.out.println(al.get()); // 7
public long getAndAdd(long delta): 先获取当前值,再进行计算val = val + delta
public long addAndGet(long delta): 先计算 val = val + delta,再返回最新值
AtomicLong al = new AtomicLong(5L); System.out.println(al.getAndAdd(4L)); // 返回现值5,再计算 System.out.println(al.addAndGet(-3L)); // 计算减法,再返回结果6
当然,这个方法也支持负数参数,也就意味着可以做减法
public long getAndUpdate (LongUnaryOperator opeartion): 使用lambda表达式进行二元运算,获取到的是旧值。
public long updateAndGet (LongUnaryOperator opeartion): 使用lambda表达式进行二元运算,获取到的是新值。
AtomicLong al = new AtomicLong(5L); System.out.println(al.getAndUpdate(x-> x + 4)); // 返回现值5,再计算 System.out.println(al.updateAndGet(x -> x - 3)); // 计算减法,再返回结果6
当然,这里支持减法也同样没问题
public long getAndAccumulate(long factor, LongBinaryOperator operation): 先返回旧值,再计算
public long accumulateAndGet(long factor, LongBinaryOperator operation): 先计算,再返回新值
AtomicLong al = new AtomicLong(5L); System.out.println(al.getAndAccumulate(4L, Long::sum)); // 返回现值5,再计算 System.out.println(al.accumulateAndGet(-3L, (a, b) -> b - a)); // 计算减法,再返回结果-12
同样,这个方法的自由度大大提高
public void set(long newVal): 直接更新为新值,区别于compareAndSet需要比对旧值。
AtomicLong al = new AtomicLong(5L); al.set(4L); System.out.println(al.get()); // 返回4
public int get(): 取最新值
附:JAVA的AtomicLong是依赖位操作的,底层不支持64位无锁操作的话,就会默认采用synchronized