/**
AtomicMarkableReference是将一个boolean值作是否有更改的标记,本质就是它的版本号只有两个, true和false,
修改的时候在这两个版本号之间来回切换,这样做并不能解决ABA的问题,只是会降低ABA问题发生的几率而已
@author : mazh
@Date : 2020/12/9 14:41
*/
public class SolveABAByAtomicMarkableReference {
private static AtomicMarkableReference atomicMarkableReference = new
AtomicMarkableReference(100, false);
public static void main(String[] args) {
Thread refT1 = new Thread(() -> {
try {TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
atomicMarkableReference.compareAndSet(100, 101,
atomicMarkableReference.isMarked(), !atomicMarkableReference.isMarked());
atomicMarkableReference.compareAndSet(101, 100,
atomicMarkableReference.isMarked(), !atomicMarkableReference.isMarked());
});
Thread refT2 = new Thread(() -> {
boolean marked = atomicMarkableReference.isMarked();
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean c3 = atomicMarkableReference.compareAndSet(100, 101,
marked, !marked);
System.out.println(c3); // 返回true,实际应该返回false
});
refT1.start();
refT2.start();
}
}
CAS ABA 问题
- 描述: 第一个线程取到了变量 x 的值 A,然后巴拉巴拉干别的事,总之就是只拿到了变量 x 的值A。这段时间内第二个线程也取到了变量 x 的值 A,然后把变量 x 的值改为 B,然后巴拉巴拉干别的事,最后又把变量 x 的值变为 A (相当于还原了)。在这之后第一个线程终于进行了变量 x 的操作,但是此时变量 x 的值还是 A,所以
compareAndSet
操作是成功。 - 例子描述(可能不太合适,但好理解): 年初,现金为零,然后通过正常劳动赚了三百万,之后正常消费了(比如买房子)三百万。年末,虽然现金零收入(可能变成其他形式了),但是赚了钱是事实,还是得交税的!
- 代码例子(以
AtomicInteger
为例)
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerDefectDemo {
public static void main(String[] args) {
defectOfABA();
}
static void defectOfABA() {
final AtomicInteger atomicInteger = new AtomicInteger(1);
Thread coreThread = new Thread(
() -> {
final int currentValue = atomicInteger.get();
System.out.println(Thread.currentThread().getName() + " ----
-- currentValue=" + currentValue);
// 这段目的:模拟处理其他业务花费的时间
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
boolean casResult = atomicInteger.compareAndSet(1, 2);
System.out.println(Thread.currentThread().getName()
+ " ------ currentValue=" + currentValue
+ ", finalValue=" + atomicInteger.get()
+ ", compareAndSet Result=" + casResult);
}
);
coreThread.start();
// 这段目的:为了让 coreThread 线程先跑起来
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread amateurThread = new Thread(
() -> {
int currentValue = atomicInteger.get();
boolean casResult = atomicInteger.compareAndSet(1, 2);
System.out.println(Thread.currentThread().getName()
+ " ------ currentValue=" + currentValue
+ ", finalValue=" + atomicInteger.get()
+ ", compareAndSet Result=" + casResult);
currentValue = atomicInteger.get();
casResult = atomicInteger.compareAndSet(2, 1);
System.out.println(Thread.currentThread().getName()
+ " ------ currentValue=" + currentValue
+ ", finalValue=" + atomicInteger.get()
+ ", compareAndSet Result=" + casResult);
}
);
amateurThread.start();
}
}
输出内容如下:
Thread-0 ------ currentValue=1
Thread-1 ------ currentValue=1, finalValue=2, compareAndSet Result=true
Thread-1 ------ currentValue=2, finalValue=1, compareAndSet Result=true
Thread-0 ------ currentValue=1, finalValue=2, compareAndSet Result=true
下面我们来详细介绍一下这些原子类。
二、基本类型原子类
1.基本类型原子类介绍
使用原子的方式更新基本类型
AtomicInteger
:整型原子类AtomicLong
:长整型原子类AtomicBoolean
:布尔型原子类
上面三个类提供的方法几乎相同,所以我们这里以AtomicInteger
为例子来介绍。
AtomicInteger 类常用方法
public final int get() //获取当前的值
public final int getAndSet(int newValue)//获取当前的值,并设置新的值
public final int getAndIncrement()//获取当前的值,并自增
public final int getAndDecrement() //获取当前的值,并自减
public final int getAndAdd(int delta) //获取当前的值,并加上预期的值
boolean compareAndSet(int expect, int update) //如果输入的数值等于预期值,则以原子方式 将该值设置为输入值(update)
public final void lazySet(int newValue)//最终设置为newValue,使用 lazySet 设置之后可能导致其他线程在之后的一小段时间内还是可以读到旧的值。
2. AtomicInteger常见方法使用
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
int temvalue = 0;
AtomicInteger i = new AtomicInteger(0);
temvalue = i.getAndSet(3);
System.out.println("temvalue:" + temvalue + "; i:" + i);//temvalue:0; i:3
temvalue = i.getAndIncrement();
System.out.println("temvalue:" + temvalue + "; i:" + i);//temvalue:3; i:4
temvalue = i.getAndAdd(5);
System.out.println("temvalue:" + temvalue + "; i:" + i);//temvalue:4; i:9
}
}
3.基本数据类型原子类的优势
通过一个简单例子带大家看一下基本数据类型原子类的优势
①多线程环境不使用原子类保证线程安全(基本数据类型)
class Test {
private volatile int count = 0;
//若要线程安全执行执行count++,需要加锁
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
②多线程环境使用原子类保证线程安全(基本数据类型)
class Test2 {
private AtomicInteger count = new AtomicInteger();
public void increment() {
count.incrementAndGet(); }
//使用AtomicInteger之后,不需要加锁,也可以实现线程安全。
public int getCount() {
return count.get();
}
}
4. AtomicInteger线程安全原理简单分析
AtomicInteger类的部分源码:
// setup to use Unsafe.compareAndSwapInt for updates(更新操作时提供“比较并替 换”的作用)
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
private volatile int value;
AtomicInteger
类主要利用CAS (compare and swap) + volatile和 native方法来保证原子操作,从而避免synchronized
的高开销,执行效率大为提升。
CAS的原理是拿期望的值和原本的一个值作比较,如果相同则更新成新的值。 UnSafe类的objectFieldOffset()
方法是一个本地方法,这个方法是用来拿到“原来的值”的内存地址。另外value是一个volatile变量,在内存中可见,因此JVM可以保证任何时刻任何线程总能拿到该变量的最新值。
三、数组类型原子类
1.数组类型原子类介绍
使用原子的方式更新数组里的某个元素
AtomicIntegerArray
:整形数组原子类AtomicLongArray
:长整形数组原子类AtomicReferenceArray
:引用类型数组原子类
上面三个类提供的方法几乎相同,所以我们这里以AtomicIntegerArray
为例子来介绍。
AtomicIntegerArray类常用方法
public final int get(int i) //获取 index=i 位置元素的值
public final int getAndSet(int i, int newValue)//返回index=i位置的当前的值,并将其设置为新值:newValue
public final int getAndIncrement(int i)//获取index=i位置元素的值,并让该位置的元素自增
public final int getAndDecrement(int i) //获取index=i位置元素的值,并让该位置的元素自减
public final int getAndAdd(int i, int delta) //获取 index=i 位置元素的值,并加上预期的值
boolean compareAndSet(int i, int expect, int update) //如果输入的数值等于预期值,则以原子方式将index=i位置的元素值设置为输入值(update)
public final void lazySet(int i, int newValue)//最终将index=i位置的元素设置为 newValue,使用lazySet设置之后可能导致其他线程在之后的一小段时间内还是可以读到旧的值。
2. AtomicIntegerArray常见方法使用
import java.util.concurrent.atomic.AtomicIntegerArray;
public class AtomicIntegerArrayTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
int temvalue = 0;
int[] nums = { 1, 2, 3, 4, 5, 6 };
AtomicIntegerArray i = new AtomicIntegerArray(nums);
for (int j = 0; j < nums.length; j++) {
System.out.println(i.get(j));
}
temvalue = i.getAndSet(0, 2);
System.out.println("temvalue:" + temvalue + "; i:" + i);
temvalue = i.getAndIncrement(0);
System.out.println("temvalue:" + temvalue + "; i:" + i);
temvalue = i.getAndAdd(0, 5);
System.out.println("temvalue:" + temvalue + "; i:" + i);
}
}
四、引用类型原子类
1.引用类型原子类介绍
基本类型原子类只能更新一个变量,如果需要原子更新多个变量,需要使用 引用类型原子类。
AtomicReference
:引用类型原子类AtomicStampedReference
:原子更新带有版本号的引用类型。该类将整数值与引用关联起来,可用于解决原子的更新数据和数据的版本号,可以解决使用CAS
进行原子更新时可能出现的ABA问题。AtomicMarkableReference
:原子更新带有标记的引用类型。该类将boolean标记与引用关联起来,也可以解决使用CAS进行原子更新时可能出现的 ABA 问题。
上面三个类提供的方法几乎相同,所以我们这里以AtomicReference
为例子来介绍。
2. AtomicReference 类使用示例
import java.util.concurrent.atomic.AtomicReference;
public class AtomicReferenceTest {
# **读者福利**
**由于篇幅过长,就不展示所有面试题了,感兴趣的小伙伴**
**关注+点赞后,[点击这里获取](https://gitee.com/vip204888/java-p7)完整面试题(含答案)!**
![35K成功入职:蚂蚁金服面试Java后端经历!「含面试题+答案」](https://img-blog.csdnimg.cn/img_convert/12c1b3f07a15f1c5723bb7db0544c5dd.png)
![35K成功入职:蚂蚁金服面试Java后端经历!「含面试题+答案」](https://img-blog.csdnimg.cn/img_convert/a836a9cef573d48df44c616840bd4242.png)
![35K成功入职:蚂蚁金服面试Java后端经历!「含面试题+答案」](https://img-blog.csdnimg.cn/img_convert/e49b163a961b807a32da0fa15742c81a.png)
**更多笔记分享**
eTest {
# **读者福利**
**由于篇幅过长,就不展示所有面试题了,感兴趣的小伙伴**
**关注+点赞后,[点击这里获取](https://gitee.com/vip204888/java-p7)完整面试题(含答案)!**
[外链图片转存中...(img-J0xZ7apv-1628340826309)]
[外链图片转存中...(img-XEUbVPHx-1628340826312)]
[外链图片转存中...(img-yElGTRdv-1628340826316)]
**更多笔记分享**
![35K成功入职:蚂蚁金服面试Java后端经历!「含面试题+答案」](https://img-blog.csdnimg.cn/img_convert/aa974bf3287abac06cb9d9f2a3db992b.png)