第32篇:原子操作增强类LongAdder、LongAccumulator

star2017 1年前 ⋅ 457 阅读

本文主要内容

  1. 4种方式实现计数器功能,对比其性能
  2. 介绍LongAdder
  3. 介绍LongAccumulator

来个需求

一个jvm中实现一个计数器功能,需保证多线程情况下数据正确性。

我们来模拟50个线程,每个线程对计数器递增100万次,最终结果应该是5000万。

我们使用4种方式实现,看一下其性能,然后引出为什么需要使用LongAdderLongAccumulator

方式一:synchronized方式实现

  1. package com.itsoku.chat32;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.concurrent.CompletableFuture;
  5. import java.util.concurrent.CountDownLatch;
  6. import java.util.concurrent.ExecutionException;
  7. import java.util.concurrent.atomic.LongAccumulator;
  8. /**
  9. * 跟着阿里p7学并发,微信公众号:javacode2018
  10. */
  11. public class Demo1 {
  12. static int count = 0;
  13. public static synchronized void incr() {
  14. count++;
  15. }
  16. public static void main(String[] args) throws ExecutionException, InterruptedException {
  17. for (int i = 0; i < 10; i++) {
  18. count = 0;
  19. m1();
  20. }
  21. }
  22. private static void m1() throws InterruptedException {
  23. long t1 = System.currentTimeMillis();
  24. int threadCount = 50;
  25. CountDownLatch countDownLatch = new CountDownLatch(threadCount);
  26. for (int i = 0; i < threadCount; i++) {
  27. new Thread(() -> {
  28. try {
  29. for (int j = 0; j < 1000000; j++) {
  30. incr();
  31. }
  32. } finally {
  33. countDownLatch.countDown();
  34. }
  35. }).start();
  36. }
  37. countDownLatch.await();
  38. long t2 = System.currentTimeMillis();
  39. System.out.println(String.format("结果:%s,耗时(ms):%s", count, (t2 - t1)));
  40. }
  41. }

输出:

  1. 结果:50000000,耗时(ms):1437
  2. 结果:50000000,耗时(ms):1913
  3. 结果:50000000,耗时(ms):386
  4. 结果:50000000,耗时(ms):383
  5. 结果:50000000,耗时(ms):381
  6. 结果:50000000,耗时(ms):382
  7. 结果:50000000,耗时(ms):379
  8. 结果:50000000,耗时(ms):379
  9. 结果:50000000,耗时(ms):392
  10. 结果:50000000,耗时(ms):384

平均耗时:390毫秒

方式2:AtomicLong实现

  1. package com.itsoku.chat32;
  2. import java.util.concurrent.CountDownLatch;
  3. import java.util.concurrent.ExecutionException;
  4. import java.util.concurrent.atomic.AtomicLong;
  5. /**
  6. * 跟着阿里p7学并发,微信公众号:javacode2018
  7. */
  8. public class Demo2 {
  9. static AtomicLong count = new AtomicLong(0);
  10. public static void incr() {
  11. count.incrementAndGet();
  12. }
  13. public static void main(String[] args) throws ExecutionException, InterruptedException {
  14. for (int i = 0; i < 10; i++) {
  15. count.set(0);
  16. m1();
  17. }
  18. }
  19. private static void m1() throws InterruptedException {
  20. long t1 = System.currentTimeMillis();
  21. int threadCount = 50;
  22. CountDownLatch countDownLatch = new CountDownLatch(threadCount);
  23. for (int i = 0; i < threadCount; i++) {
  24. new Thread(() -> {
  25. try {
  26. for (int j = 0; j < 1000000; j++) {
  27. incr();
  28. }
  29. } finally {
  30. countDownLatch.countDown();
  31. }
  32. }).start();
  33. }
  34. countDownLatch.await();
  35. long t2 = System.currentTimeMillis();
  36. System.out.println(String.format("结果:%s,耗时(ms):%s", count, (t2 - t1)));
  37. }
  38. }

输出:

  1. 结果:50000000,耗时(ms):971
  2. 结果:50000000,耗时(ms):915
  3. 结果:50000000,耗时(ms):920
  4. 结果:50000000,耗时(ms):923
  5. 结果:50000000,耗时(ms):910
  6. 结果:50000000,耗时(ms):916
  7. 结果:50000000,耗时(ms):923
  8. 结果:50000000,耗时(ms):916
  9. 结果:50000000,耗时(ms):912
  10. 结果:50000000,耗时(ms):908

平均耗时:920毫秒

AtomicLong内部采用CAS的方式实现,并发量大的情况下,CAS失败率比较高,导致性能比synchronized还低一些。并发量不是太大的情况下,CAS性能还是可以的。

AtomicLong属于JUC中的原子类,还不是很熟悉的可以看一下:JUC中原子类,一篇就够了

方式3:LongAdder实现

先介绍一下LongAdder,说到LongAdder,不得不提的就是AtomicLong,AtomicLong是JDK1.5开始出现的,里面主要使用了一个long类型的value作为成员变量,然后使用循环的CAS操作去操作value的值,并发量比较大的情况下,CAS操作失败的概率较高,内部失败了会重试,导致耗时可能会增加。

LongAdder是JDK1.8开始出现的,所提供的API基本上可以替换掉原先的AtomicLong。LongAdder在并发量比较大的情况下,操作数据的时候,相当于把这个数字分成了很多份数字,然后交给多个人去管控,每个管控者负责保证部分数字在多线程情况下操作的正确性。当多线程访问的时,通过hash算法映射到具体管控者去操作数据,最后再汇总所有的管控者的数据,得到最终结果。相当于降低了并发情况下锁的粒度,所以效率比较高,看一下下面的图,方便理解:

代码:

  1. package com.itsoku.chat32;
  2. import java.util.concurrent.CountDownLatch;
  3. import java.util.concurrent.ExecutionException;
  4. import java.util.concurrent.atomic.AtomicLong;
  5. import java.util.concurrent.atomic.LongAdder;
  6. /**
  7. * 跟着阿里p7学并发,微信公众号:javacode2018
  8. */
  9. public class Demo3 {
  10. static LongAdder count = new LongAdder();
  11. public static void incr() {
  12. count.increment();
  13. }
  14. public static void main(String[] args) throws ExecutionException, InterruptedException {
  15. for (int i = 0; i < 10; i++) {
  16. count.reset();
  17. m1();
  18. }
  19. }
  20. private static void m1() throws ExecutionException, InterruptedException {
  21. long t1 = System.currentTimeMillis();
  22. int threadCount = 50;
  23. CountDownLatch countDownLatch = new CountDownLatch(threadCount);
  24. for (int i = 0; i < threadCount; i++) {
  25. new Thread(() -> {
  26. try {
  27. for (int j = 0; j < 1000000; j++) {
  28. incr();
  29. }
  30. } finally {
  31. countDownLatch.countDown();
  32. }
  33. }).start();
  34. }
  35. countDownLatch.await();
  36. long t2 = System.currentTimeMillis();
  37. System.out.println(String.format("结果:%s,耗时(ms):%s", count.sum(), (t2 - t1)));
  38. }
  39. }

输出:

  1. 结果:50000000,耗时(ms):206
  2. 结果:50000000,耗时(ms):105
  3. 结果:50000000,耗时(ms):107
  4. 结果:50000000,耗时(ms):107
  5. 结果:50000000,耗时(ms):105
  6. 结果:50000000,耗时(ms):99
  7. 结果:50000000,耗时(ms):106
  8. 结果:50000000,耗时(ms):102
  9. 结果:50000000,耗时(ms):106
  10. 结果:50000000,耗时(ms):102

平均耗时:100毫秒

代码中new LongAdder()创建一个LongAdder对象,内部数字初始值是0,调用increment()方法可以对LongAdder内部的值原子递增1。reset()方法可以重置LongAdder的值,使其归0。

方式4:LongAccumulator实现

LongAccumulator介绍

LongAccumulator是LongAdder的功能增强版。LongAdder的API只有对数值的加减,而LongAccumulator提供了自定义的函数操作,其构造函数如下:

  1. /**
  2. * accumulatorFunction:需要执行的二元函数(接收2个long作为形参,并返回1个long)
  3. * identity:初始值
  4. **/
  5. public LongAccumulator(LongBinaryOperator accumulatorFunction, long identity) {
  6. this.function = accumulatorFunction;
  7. base = this.identity = identity;
  8. }

示例代码:

  1. package com.itsoku.chat32;
  2. import java.util.concurrent.CountDownLatch;
  3. import java.util.concurrent.ExecutionException;
  4. import java.util.concurrent.atomic.LongAccumulator;
  5. import java.util.concurrent.atomic.LongAdder;
  6. /**
  7. * 跟着阿里p7学并发,微信公众号:javacode2018
  8. */
  9. public class Demo4 {
  10. static LongAccumulator count = new LongAccumulator((x, y) -> x + y, 0L);
  11. public static void incr() {
  12. count.accumulate(1);
  13. }
  14. public static void main(String[] args) throws ExecutionException, InterruptedException {
  15. for (int i = 0; i < 10; i++) {
  16. count.reset();
  17. m1();
  18. }
  19. }
  20. private static void m1() throws ExecutionException, InterruptedException {
  21. long t1 = System.currentTimeMillis();
  22. int threadCount = 50;
  23. CountDownLatch countDownLatch = new CountDownLatch(threadCount);
  24. for (int i = 0; i < threadCount; i++) {
  25. new Thread(() -> {
  26. try {
  27. for (int j = 0; j < 1000000; j++) {
  28. incr();
  29. }
  30. } finally {
  31. countDownLatch.countDown();
  32. }
  33. }).start();
  34. }
  35. countDownLatch.await();
  36. long t2 = System.currentTimeMillis();
  37. System.out.println(String.format("结果:%s,耗时(ms):%s", count.longValue(), (t2 - t1)));
  38. }
  39. }

输出:

  1. 结果:50000000,耗时(ms):138
  2. 结果:50000000,耗时(ms):111
  3. 结果:50000000,耗时(ms):111
  4. 结果:50000000,耗时(ms):103
  5. 结果:50000000,耗时(ms):103
  6. 结果:50000000,耗时(ms):105
  7. 结果:50000000,耗时(ms):101
  8. 结果:50000000,耗时(ms):106
  9. 结果:50000000,耗时(ms):102
  10. 结果:50000000,耗时(ms):103

平均耗时:100毫秒

LongAccumulator的效率和LongAdder差不多,不过更灵活一些。

调用new LongAdder()等价于new LongAccumulator((x, y) -> x + y, 0L)

从上面4个示例的结果来看,LongAdder、LongAccumulator全面超越同步锁及AtomicLong的方式,建议在使用AtomicLong的地方可以直接替换为LongAdder、LongAccumulator,吞吐量更高一些。

最新资料

更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: