简体   繁体   English

原子性 - 锁定 Vs 原子 Vs 二进制信号量 - 性能

[英]Atomicity - Lock Vs atomic Vs binary-semaphore - Performance

Monitor = mutex(lock) + condition variable Monitor = mutex(lock) + 条件变量

Each Java object has a monitor, holding above principle.每个 Java 对象都有一个监视器,遵循上述原则。

synchronized key word claim a monitor(lock + conditionvar) of an object. synchronized关键字声明对象的监视器(锁定 + 条件变量)。

My understanding is, for atomicity, conditionvar is not required, lock(mutex) would suffice.我的理解是,对于原子性,不需要条件变量,lock(mutex) 就足够了。


To maintain atomicity of a memory area, Java provides Lock , atomic package and binary semaphore .为了保持内存区域的原子性,Java 提供了Lockatomic package 和binary semaphore

For atomicity, Which approach is better in terms of performance?对于原子性,哪种方法在性能方面更好?

It depends on the access pattern: synchronized(var) { ... } is the simplest to use as it doesn't require explicit unlock, unlike ReentrantLock .这取决于访问模式: synchronized(var) { ... }使用起来最简单,因为它不需要显式解锁,与ReentrantLock不同。 Those two are the same: synchronized(var) will grab a lock on var , while Lock will grab a lock on "itself" (so to say).这两个是相同的: synchronized(var)将在var上获取锁,而Lock将在“自身”上获取锁(可以这么说)。 But the ReentrantLock allows you to get extended information (see its javadoc for more information: isHeldByCurrentThread() and getHoldCount() ).但是ReentrantLock允许您获取扩展信息(有关更多信息,请参阅其javadocisHeldByCurrentThread()getHoldCount() )。

Performance-wise, ReentrantReadWriteLock will improve performance when you have few writes and many reads (as you don't need to lock when you're only reading), but you should take extra care when taking and releasing locks, as "ownable synchronizers" can deadlock your threads (read and write locks are not treated in the same manner).在性能方面, ReentrantReadWriteLock将在您写入很少和读取很多时提高性能(因为当您只读取时不需要锁定),但在获取和释放锁时应格外小心,作为“可拥有的同步器”可能会使您的线程死锁(读取和写入锁的处理方式不同)。

But if the data you want to read/write is a "simple type" (as described in the atomic package javadoc ), you will get the best performance by using the AtomicInteger and the likes, as they use specific, optimized CPU instruction set such as compare-and-swap in SSE* set.但是,如果您要读/写的数据是“简单类型”(如原子包 javadoc 中所述),您将通过使用AtomicInteger等获得最佳性能,因为它们使用特定的、优化的 CPU 指令集,例如作为 SSE* 集中的比较和交换

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM