Reputation: 9542
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?
Upvotes: 5
Views: 4539
Reputation: 1215
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.
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.
Upvotes: 1
Reputation: 533870
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)
Upvotes: 9
Reputation: 727047
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.
Upvotes: 8