[concurrency-interest] RentrantLock performance vs. AtomicInt

Brian Goetz brian at quiotix.com
Sat Feb 4 16:56:01 EST 2006


A good way to think of it:
  - Atomics do better at low contention;
  - Locks do better at high contention, because blocking takes the 
current thread out of contention.

With atomics, if you have 16 thread pounding on a memory location, 15 
will lose and one will make progress, but you get a _lot_ of 
synchronization traffic on the memory bus.  With locks, 15 of those 
threads will block, which means they are no longer pounding on the lock, 
and then when the lock is released _one_ will be awakened and allowed to 
proceed.  Its less of a free-for-all, which generates less bus traffic.

But be aware that this sort of pound-on-a-memory-location test is not a 
realistic test for locks vs atomics -- no one uses them in this way. 
Add in some real, thread-local work to your tasks, and you'll see 
Atomics pull ahead.

studdugie wrote:
> I recently re-read an IBM publication on the (then) new concurrency
> utilities in Java 1.5
> [http://www-128.ibm.com/developerworks/edu/j-dw-java-concur-i.html].
> In it there was a graph comparing the throughput of AtomicLong vs
> synchronized vs RentrantLock. I was surprised to see how quickly the
> throughput of AtomicLong dropped as contention increased.
> 
> Given that the article is more than a year old I decided to run my own
> benchmarks on the latest and greatest JVM to see if the conclusions
> suggested by the graph still hold true. Unfortunately, they still do.
> My micro benchmark isn't as sophisticated as the IBM's, it simply
> computes the sum of 10,000,000 by incrementing an integer from
> 0-10000000. I've wrote 3 variations. One is protected by a
> synchronized block, the other an AtomicInteger and AtomicLong, and
> finally a ReentrantLock. I'm having trouble groking why ReentrantLock
> is so much faster than the Atomic objects as the number of threads
> increase. I looked through the ReentrackLock source and it's built
> around similiar CAS calls as the Atomic classes, so why is it so much
> faster?
> 
> Examples
> ======
> 4 Threads:
> Atomic: 1sec 279millis 974micro
> sync: 1sec 646millis 609micro
> Lock: 479millis 566micro
> 
> 8 Threads:
> Atomic: 1sec 202millis 359micro
> sync: 2sec 154millis 382micro
> Lock: 418millis 975micro
> 
> 16 Threads:
> Atomic:1sec 113millis 365micro
> sync: 2sec 19millis 532micro
> Lock: 385millis 13micro
> 
> All the tests were run on the following platform:
> CPU: AMD64 Operteron 270 dual processor/dual core (4CPUS)
> RAM: 12GB
> OS: GNU/Linux kernel 2.6.14.2
> JVM: Java HotSpot 64-Bit Server VM (build 1.5.0_06-b05)
> 
> _______________________________________________
> Concurrency-interest mailing list
> Concurrency-interest at altair.cs.oswego.edu
> http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest



More information about the Concurrency-interest mailing list