dabadaba
dabadaba

Reputation: 9542

synchronized vs ReentrantLock vs AtomicInteger execution time

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

Answers (3)

Simone Casagranda
Simone Casagranda

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.

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.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533870

A number of factor effect this.

  • the version of Java. Java 5.0 was much faster for ReentrantLock, Java 7 not so much
  • the level of contention. synchronized works best (as does locking in general) with low contention rates. ReentrantLock works better with higher contention rates. YMWV
  • how much optimisation can the JIT do. The JIT optimise synchronized in ways ReentrantLOck is not. If this is not possible you won't see the advantage.
  • synchronized is GC free in it's actions. ReentrantLock can create garbage which can make it slower and trigger GCs depending on how it is used.

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

Sergey Kalinichenko
Sergey Kalinichenko

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

Related Questions