Java 1亿次原子性自增悲观锁、乐观锁、可重入锁的性能比较分析

github代码

系统配置、使用类、JDK

系统:windows7
处理器:Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz 3.40GHz
内存(RAM):8.00G
系统类型:64位操作系统
悲观锁:synchronized
乐观锁:AtomicInteger、LongAdder
JDK:1.7、1.8

结果分析

  1. JDK1.8中乐观锁优化后的LongAdder性能最好。
  2. 相同系统配置、JDK环境条件下悲观锁synchronized的性能最差,乐观锁AtomicInteger和可重入锁ReentrantLock性能相差不大,LongAdder性能最好。
  3. 悲观锁synchronized在JDK1.7和JDK1.8中的性能相差不多。
  4. 乐观锁AtomicInteger在JDK1.7和JDK1.8中的性能相差极大,在JDK1.7中高并发的情况下甚至没有悲观锁synchronized的性能好。
  5. 线程数的增加对性能有一定的影响但有限。

测试数据

Java类 线程数 循环次数 1~10次的运行时间 平均时间
AtomicInteger(JDK1.8) 10 10000000 2234 2456 2372 2197 2405 2390 2227 2407 2379 2221 2328
100 1000000 2452 2462 2433 2260 2442 2488 2479 2229 2460 2192 2388
1000 100000 2462 2266 2495 2479 2434 2472 2435 2484 2432 2447 2440
LongAdder(JDK1.8) 10 10000000 231 249 241 221 245 265 245 228 242 246 241
100 1000000 230 229 219 231 215 230 241 216 223 246 228
1000 100000 239 241 259 242 234 266 275 235 247 248 248
synchronized(JDK1.8) 10 10000000 3885 3784 3890 3769 3846 4049 3875 3725 3913 3762 3849
100 1000000 3842 3802 3951 3776 4061 3859 3870 3872 3815 3857 3870
1000 100000 3942 3940 3912 3977 3757 3897 3987 3915 3945 3917 3918
ReentrantLock(JDK1.8) 10 10000000 2698 2477 2609 2609 2524 2478 2562 2509 2577 2489 2533
100 1000000 2539 2515 2510 2550 2539 2367 2557 2495 2564 2544 2518
1000 100000 2402 2331 2356 2377 2408 2386 2358 2378 2345 2376 2371
AtomicInteger(JDK1.7) 10 10000000 8855 9200 9532 8955 8755 8911 9400 8621 9129 8532 8989
100 1000000 10024 10289 9096 9050 10256 9500 9869 10095 10243 9400 9782
1000 100000 10233 10488 10352 10113 10423 10324 10329 10423 10520 10245 10345
synchronized(JDK1.7) 10 10000000 3815 3684 3990 3469 3823 3919 3871 3755 3813 3769 3790
100 1000000 3982 3872 3451 3916 3761 3801 3970 3892 3715 3957 3831
1000 100000 3989 3978 3852 3897 3817 3977 3838 3745 3969 3971 3903

猜你喜欢

转载自blog.csdn.net/qq_27243963/article/details/94719016
今日推荐