一 AtomicInteger
public class AtomicIntegerExample{
// 请求总数
public static int clientTotal = 5000;
// 同时并发执行的线程数
public static int threadTotal = 200;
public static AtomicInteger count = new AtomicInteger(0);
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();
add();
semaphore.release();
} catch (Exception e) {
log.error("exception", e);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
log.info("count:{}", count.get());
}
private static void add() {
count.incrementAndGet();
// count.getAndIncrement();
}
}
cas原理完成原子性(compareAndSwapInt)
主要是执行了一个do-while循环,compareAndSwapInt(var1,var2,var5,var5+var4)
说明:var1是传入的AtomicInteger对象,var2是当前值,var4是要增加的值,比如1,var5是当前底层主内存的值,如果var2和var5值相等时,执行var5加上var4,否则不断循环判断。
二 AtomicLong和LongAdder
AtomicLong是在一个死循环里保证安全性,竞争不激烈的情况下成功概率很高。准确数值的时候
LongAdder:统计数据会有误差,高并发效率高
三 AtomicReference和 AtomicIntegerFieldUpdater
public class AtomicReferenceExample{
private static AtomicReference<Integer> count = new AtomicReference<>(0);
public static void main(String[] args) {
count.compareAndSet(0, 2); // 2
count.compareAndSet(0, 1); // no
count.compareAndSet(1, 3); // no
count.compareAndSet(2, 4); // 4
count.compareAndSet(3, 5); // no
log.info("count:{}", count.get());
}
}
更新某个类的字段,要求字段是非static,volatile修饰
public class AtomicExample5 {
private static AtomicIntegerFieldUpdater<AtomicExample5> updater =
AtomicIntegerFieldUpdater.newUpdater(AtomicExample5.class, "count");
@Getter
public volatile int count = 100;
public static void main(String[] args) {
AtomicExample5 example5 = new AtomicExample5();
if (updater.compareAndSet(example5, 100, 120)) {
log.info("update success 1, {}", example5.getCount());
}
if (updater.compareAndSet(example5, 100, 120)) {
log.info("update success 2, {}", example5.getCount());
} else {
log.info("update failed, {}", example5.getCount());
}
}
}
四 AtomicStampReference和AtomicMarkableReference:CAS的ABA问题
Thread1:A->B-A
Thead2:A->C
ABA问题:和我们数据库中用的多版本并发控制,使用乐观锁加一个 version 字段类似,比如InnoDB每一行会保存一个创建和删除的版本号,数据查询的时候会根据这两个版本号查询。
场景:
一个链表A-B-C,线程1准备将链表头结点换成B,执行CAS操作head.compareAndSet(A,B); 在执行该语句之前,线程2介入,并通过CAS操作将
head.compareAndSet(B,C); 此时链表为A-C,B节点被拿出了此时切回线程1,线程1发现,A没有发生改变还是A,则将A换成了B,此时B-next为null,节点C也被无辜删除了。总结来说就是:链表的改变没有在head上反映出来,head没有改变,但是链表却改变了。
AtomicStampedReference 中的版本号 stamp 是一个 int 类型
AtomicMarkableReference 中的版本号 mark 则是一个 boolean 类型
五 AtomicLongArray 数组 索引
六 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");
}
}
}