I can see that ReentrantLock
is around 50% faster than synchronized
and AtomicInteger
100% faster. Why such difference with the execution time of these three synchronization methods: synchronized
blocks, ReentrantLock
and AtomicInteger
(or whatever class from the Atomic
package).
Are there any other popular and extended synchronizing methods aside than these ones?
A number of factor effect this.
AtomicInteger uses the same primitives that locking uses but does a busy wait. CompareAndSet also called CompareAndSwap i.e. it is much simpler in what it does (and much more limited as well)
The ConcurrentXxxx, CopyOnWriteArrayXxxx collections are very popular. These provide concurrency without needing to use lock directly (and in some cases no locks at all)
AtomicInteger
is much faster than the other two synchronization methods on your hardware because it is lock-free. On architectures where the CPU provides basic facilities for lock-free concurrency, AtomicInteger
's operations are performed entirely in hardware, with the critical usually taking a single CPU instruction. In contrast, ReentrantLock
and synchronized
use multiple instructions to perform their task, so you see some considerable overhead associated with them.
I think that you are doing a common mistake evaluating those 3 elements for comparison.
Basically when a ReentrantLock is something that allows you more flexibility when your are synchronizing blocks compared with the synchronized key. Atomic is something that adopts a different approach based on CAS(Compare and Swap) to manage the updates in a concurrent context.
I suggest you to read in deep a bible of concurrency for the Java platform.
Java Concurrency in Practice - Brian Göetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes & Doug Lea
There's a lot difference in having a deep knowledge on concurrency and know what a language can offer you to solve concurrency problems and taking advantage of multithreading.
In terms of performance, it depends on the current scenario.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With