1 Atomic原子类概述
JDK1.5开始出现
1.1 Atomic原子类分类
- 1 原子更新基本类型
- 2 原子更新数组
- 3 原子更新抽象类型
- 4 原子更新字段
1.2 Atomic原子类所在位置
2.Atomic原子类代码演示
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReference;
public class AtomicSequence {
private static boolean test1Flag = false;
private static boolean test2Flag = false;
private static boolean test3Flag = true;
private static boolean test4Flag = false;
//1.原子更新基本类型 -- Integer的原子类,
private AtomicInteger atomicIntegerValue = new AtomicInteger(0);
//1.1 没有char类的原子性,转换成char的unicode码后用integer来实现
//2.原子更新数组
private int [] integerArray = {1,2,10,5};
AtomicIntegerArray atomicIntegerArray = new AtomicIntegerArray(integerArray);
//3.原子更新抽象类型,对用户进行原子操作,是对用户里面的属性进行原子操作
AtomicReference<User> atomicReferenceUser = new AtomicReference<>();
User userTemp = new User();
//4.原子更新字段-对象的属性字段
AtomicIntegerFieldUpdater<User> atomicIntegerFieldUpdaterUserAge = AtomicIntegerFieldUpdater.newUpdater(User.class, "age");
//1.AtomicInteger
public int getNextAtomicInteger() {
Integer value1 = atomicIntegerValue.getAndIncrement(); //返回并递增
Integer value2 = atomicIntegerValue.incrementAndGet(); //递增并返回
Integer value3 = atomicIntegerValue.getAndDecrement(); //返回并递减
Integer value4 = atomicIntegerValue.getAndAdd(10); //递增+10
return value1; //返回并递增
}
//1-2.AtomicInteger-->String
public void getNextAtomicIntegerString(){
System.out.println("atomicIntegerValue.toString()->"+atomicIntegerArray.toString());
}
//2.数组
public Integer getNextAtomicIntegerArray() {
Integer value1 = atomicIntegerArray.getAndIncrement(0); //指定位置增加值1(从0开始)
Integer value2 = atomicIntegerArray.getAndAdd(2, 10);//指定位置增加指定值
Integer value3 = atomicIntegerArray.addAndGet(3,5);//指定位置添加并获取
return value1;
}
//3.原子更新抽象类型属性,
public Integer getNextAtomicIntegerFieldUpdater() {
Integer userAge = atomicIntegerFieldUpdaterUserAge.getAndIncrement(userTemp);
System.out.println("userage->"+userAge);
return userAge;
}
public static void main(String[] args) {
AtomicSequence atomicSequence = new AtomicSequence();
new Thread(new Runnable() {
//atomicSequence.getNextAtomicInteger()可以演示多线程,然后会发现线程安全
@Override
public void run() {
for(int i =0;i<20;i++) {
if(test1Flag) {
//1-1.获取原子更新基本类型线程1
System.out.println(Thread.currentThread().getName() + "原子Integer结果为-:" + atomicSequence.getNextAtomicInteger());
}
if(test2Flag) {
//2-1.获取原子更新数组类型线程1
System.out.println(Thread.currentThread().getName() + "原子数组类型结果为--:" + atomicSequence.getNextAtomicIntegerArray());
}
if(test3Flag) {
//3-1.获取原子引用类型属性值线程1
System.out.println(Thread.currentThread().getName() + "原子引用类型属性值结果为---:" + atomicSequence.getNextAtomicIntegerFieldUpdater());
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i =0;i<20;i++) {
if(test1Flag) {
//1-2获取原子更新基本类型线程2
System.out.println(Thread.currentThread().getName() + "原子Integer结果为-:" + atomicSequence.getNextAtomicInteger());
}
if(test2Flag) {
//2-2.获取原子更新数组类型线程2
System.out.println(Thread.currentThread().getName() + "原子数组类型结果为--:" + atomicSequence.getNextAtomicIntegerArray());
}
if(test3Flag) {
//3-2.获取原子引用类型属性值线程2
System.out.println(Thread.currentThread().getName() + "原子引用类型属性值结果为---:" + atomicSequence.getNextAtomicIntegerFieldUpdater());
}
}
}
}).start();
new Thread(){
@Override
public void run() {
for(int i =0;i<20;i++) {
if(test1Flag) {
//1-3获取原子更新基本类型线程3
System.out.println(Thread.currentThread().getName() + "原子Integer结果为-:" + atomicSequence.getNextAtomicInteger());
}
if(test2Flag) {
//2-3.获取原子更新数组类型线程3
System.out.println(Thread.currentThread().getName() + "原子数组类型结果为---:" + atomicSequence.getNextAtomicIntegerArray());
}
if(test3Flag) {
//3-3.获取原子引用类型属性值线程3
System.out.println(Thread.currentThread().getName() + "原子引用类型属性值结果为---:" + atomicSequence.getNextAtomicIntegerFieldUpdater());
}
}
}
}.start();
}
}
public class User {
private String name;
//注意声明为volatile
public volatile int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
3.Atomic源码简介
大量用到了unsafe的api.和CAS.unsafe为不公开源码.
源码:
public class AtomicInteger extends Number implements java.io.Serializable {
public final int getAndUpdate(IntUnaryOperator updateFunction) {
int prev, next;
do {
//获取当前值
prev = get();
//获取next值
next = updateFunction.applyAsInt(prev);
//CAS,把当前值和期待的下一个值CAS,
//如果为true就返回prev,如果返回false,则继续重试.
} while (!compareAndSet(prev, next));
return prev;
}
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
public final int get() {
return value;
}
}
4. LongAddr(JDK8开始)
4.1 Atomic原子类的缺点
由于Atomic用到了如下自旋,在高并发的情况下性能不好.
do {
prev = get();
next = updateFunction.applyAsInt(prev);
} while (!compareAndSet(prev, next));
4.2 LongAddr概述
LongAddr开始出现,同时还有DoubleAdder
4.4 源码
public class LongAdder extends Striped64 implements Serializable {
public void increment() {
add(1L);
}
public void decrement() {
add(-1L);
}
public void add(long x) {
//定义变量
Cell[] as; long b, v; int m; Cell a;
//as赋值等于cells,如果不为空(说明并发中的不是第一次);或者casBase(原子设置b=base,b+x)不成功
//㘝casBase设置完成则完成返回
if ((as = cells) != null || !casBase(b = base, b + x)) {
boolean uncontended = true;
if (as == null || (m = as.length - 1) < 0 ||
(a = as[getProbe() & m]) == null ||
!(uncontended = a.cas(v = a.value, v + x)))
//longAccumulate是计算的核心方法
longAccumulate(x, null, uncontended);
}
}
public int intValue() {
return (int)sum();
}
public long sum() {
Cell[] as = cells; Cell a;
long sum = base;
if (as != null) {
for (int i = 0; i < as.length; ++i) {
if ((a = as[i]) != null)
sum += a.value;
}
}
return sum;
}
}
class Striped64{
longAccumulate
}
4.5 LongAddr原理
LongAddr有多个值,可以竞争的资源多,抢到的概率大,如果抢占不到,还可能扩容.
有一个base值,然后多一个值cell,高并发时用多个cell累加
Java并发编程笔记之LongAdder和LongAccumulator源码探究
LongAdder源码分析(只分析了两个方法,add和longAccumulate,也是核心方法)