简体   繁体   中英

Atomicity - Lock Vs atomic Vs binary-semaphore - Performance

Monitor = mutex(lock) + condition variable

Each Java object has a monitor, holding above principle.

synchronized key word claim a monitor(lock + conditionvar) of an object.

My understanding is, for atomicity, conditionvar is not required, lock(mutex) would suffice.


To maintain atomicity of a memory area, Java provides Lock , atomic package and 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 . Those two are the same: synchronized(var) will grab a lock on var , while Lock will grab a lock on "itself" (so to say). But the ReentrantLock allows you to get extended information (see its javadoc for more information: isHeldByCurrentThread() and 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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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