项目场景:

使用LongAdder本地保存数据,定时的去拉取本地缓存中的数据更新到数据库。

虽然LongAdder的性能比AtomicInteger更好,但是LongAdder获取的值不是准确值
累加器性能比较

  1. public class Test41 {
  2. public static void main(String[] args) {
  3. for (int i = 0; i < 5; i++) {
  4. demo(
  5. () -> new AtomicLong(0),
  6. (adder) -> adder.getAndIncrement()
  7. );
  8. }
  9. for (int i = 0; i < 5; i++) {
  10. demo(
  11. () -> new LongAdder(),
  12. adder -> adder.increment()
  13. );
  14. }
  15. }
  16. /*
  17. () -> 结果 提供累加器对象
  18. (参数) -> 执行累加操作
  19. */
  20. private static <T> void demo(Supplier<T> adderSupplier, Consumer<T> action) {
  21. T adder = adderSupplier.get();
  22. List<Thread> ts = new ArrayList<>();
  23. // 4 个线程,每人累加 50 万
  24. for (int i = 0; i < 4; i++) {
  25. ts.add(new Thread(() -> {
  26. for (int j = 0; j < 500000; j++) {
  27. action.accept(adder);
  28. }
  29. }));
  30. }
  31. long start = System.nanoTime();
  32. ts.forEach(t -> t.start());
  33. ts.forEach(t -> {
  34. try {
  35. t.join();
  36. } catch (InterruptedException e) {
  37. e.printStackTrace();
  38. }
  39. });
  40. long end = System.nanoTime();
  41. System.out.println(adder + " cost:" + (end - start) / 1000_000);
  42. }
  43. }

2000000 cost:35 2000000 cost:29 2000000 cost:32 2000000 cost:33 2000000 cost:30 2000000 cost:9 2000000 cost:5 2000000 cost:5 2000000 cost:4 2000000 cost:3