它是native修饰的,代表是java底层的方法,不是通过java实现的 。
再重新看getAndAddInt(),传来第一个值是当前的一个对象 ,比如是count.incrementAndGet(),那么在getAndAddInt()中,var1就是count,而var2第二个值是当前的值,比如想执行的是2+1=3操作,那么第二个参数是2,第三个参数是1 。
变量5(var5)是我们调用底层的方法而得到的底层当前的值,如果没有别的线程过来处理我们count变量的时候,那么它正常返回值是2。
因此传到compareAndSwapInt方法里的参数是(count对象,当前值2,当前从底层传过来的2,从底层取出来的值加上改变量var4)。
compareAndSwapInt()希望达到的目标是对于var1对象,如果当前的值var2和底层的值var5相等,那么把它更新成后面的值(var5+var4).
compareAndSwapInt核心就是CAS核心。
关于count值为什么和底层值不一样:count里面的值相当于存在于工作内存的值,底层就是主内存。
(2)AtomicStampedReference
=========================
接下来我们看一下AtomicStampedReference。
关于CAS有一个ABA问题:开始是A,后来改为B,现在又改为A。解决办法就是:每次变量改变的时候,把变量的版本号加1。
这就用到了AtomicStampedReference。
我们来看AtomicStampedReference里的compareAndSet()实现:
而在AtomicInteger里compareAndSet()实现:
可以看到AtomicStampedReference里的compareAndSet()中多了 一个stamp比较(也就是版本),这个值是由每次更新时来维护的。
(3)AtomicLongArray
==================
这种维护数组的atomic类,我们可以选择性地更新其中某一个索引对应的值,也是进行原子性操作。这种对数组的操作的各种方法,会多处一个索引。
比如,我们看一下compareAndSet():
(4)AtomicBoolean
================
看一段代码:
public class AtomicBooleanExample {
private static AtomicBoolean isHappened = new AtomicBoolean(false);
// 请求总数
public static int clientTotal = 5000;
// 同时并发执行的线程数
public static int threadTotal = 200;
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(threadTotal);
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
for (int i = 0; i < clientTotal ; i++) {
executorService.execute(() -> {
try {
semaphore.acquire();
test();
semaphore.release();
} catch (Exception e) {
log.error(“exception”, e);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
log.info(“isHappened:{}”, isHappened.get());
}
private static void test() {
if (isHappened.compareAndSet(false, true)) {
log.info(“execute”);
}
}
}
执行之后发现,log.info(“execute”);只执行了一次,且isHappend值为true。
原因就是当它第一次compareAndSet()之后,isHappend变为true,没有别的线程干扰。
通过使用AtomicBoolean,我们可以使某段代码只执行一次。
三、原子性—synchronized
====================
synchronized是一种同步锁,通过锁实现原子操作。
JDK提供锁分两种:一种是synchronized,依赖JVM实现锁,因此在这个关键字作用对象的作用范围内是同一时刻只能有一个线程进行操作;另一种是LOCK,是JDK提供的代码层面的锁,依赖CPU指令,代表性的是ReentrantLock。
synchronized修饰的对象有四种:
-
修饰代码块,作用于调用的对象;
-
修饰方法,作用于调用的对象;
-
修饰静态方法,作用于所有对象;
-
修饰类,作用于所有对象。
修饰代码块和方法:
@Slf4j
public class SynchronizedExample1 {
// 修饰一个代码块
public void test1(int j) {
synchronized (this) {
for (int i = 0; i < 10; i++) {
log.info(“test1 {} - {}”, j, i);
}
}
}
// 修饰一个方法
public synchronized void test2(int j) {
for (int i = 0; i < 10; i++) {
log.info(“test2 {} - {}”, j, i);
}
}
public static void main(String[] args) {
SynchronizedExample1 example1 = new SynchronizedExample1();
SynchronizedExample1 example2 = new SynchronizedExample1();
ExecutorService executorService = Executors.newCachedThreadPool();
//一
executorService.execute(() -> {
example1.test1(1);
});
executorService.execute(() -> {
example1.test1(2);
});
//二
executorService.execute(() -> {
example2.test2(1);
});
executorService.execute(() -> {
example2.test2(2);
});
//三
executorService.execute(() -> {
example1.test1(1);
});
executorService.execute(() -> {
example2.test1(2);
});
}
}
执行后可以看到对于情况一,test1内部方法块作用于example1,先执行完一次0-9输出,再执行下一次0-9输出;情况二,同情况一类似,作用于example2;情况三,可以看到交叉执行,test1分别独立作用于example1和example2,互不影响。
修饰静态方法和类:
@Slf4j
public class SynchronizedExample2 {
// 修饰一个类
public static void test1(int j) {
synchronized (SynchronizedExample2.class) {
for (int i = 0; i < 10; i++) {
log.info(“test1 {} - {}”, j, i);
}
}
}
// 修饰一个静态方法
public static synchronized void test2(int j) {
for (int i = 0; i < 10; i++) {
log.info(“test2 {} - {}”, j, i);
}
}
public static void main(String[] args) {
SynchronizedExample2 example1 = new SynchronizedExample2();
SynchronizedExample2 example2 = new SynchronizedExample2();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> {
example1.test1(1);
});
executorService.execute(() -> {
example2.test1(2);
});
}
}
test1和test2会锁定调用它们的对象所属的类,同一个时间只有一个对象在执行。
四、可见性—volatile
================
对于可见性,JVM提供了synchronized和volatile。这里我们看volatile。
(1)volatile的可见性是通过内存屏障和禁止重排序实现的
===============================
volatile会在写操作时,会在写操作后加一条store屏障指令,将本地内存中的共享变量值刷新到主内存:
volatile在进行读操作时,会在读操作前加一条load指令,从内存中读取共享变量:
(2)但是volatile不是原子性的,进行++操作不是安全的
===============================
@Slf4j
public class VolatileExample {
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!