Fastest way to lock/synchronize objects.

Overview


There have been some comparison of Lock vs synchronization in Java. I wanted to compare the latest version of Java with using a plain AtomicLong and AtomicReference as an alternative to locking.


Summary

The results are much the same for Java 5.0 and later, provided your JIT has optimised the code. I found this required the methods to be called between 10K and 50K times to get the best optmisation (depending on the approach used)

In short, the fastest way to perform lock/synchronization is to make sure your JVM is warmed up first.


Results

The tests were single threaded and run on a 3 GHz Xeon processor running SLES 11.

Timings are in nano-seconds, that is one billionth of a second. For Java 1.4.2 I used the backport v2.1

Versionbits concurrent Lock synchronized AtomicLong AtomicReference
1.4.2 u 18 32 130 40 115 105
5.0 u 22 64 23 15 15 16
6 u 764 21 20 14 15
6 u 20 32 23 20 19 12
6 u 20 64 16 20 12 13
7 eap b76 32 23 20 19 12

Comments

  1. Afaik a intrinsic lock (so a synchronized statement or method) has support for biased locking, making acquiring a lock the second time by the same thread much cheaper.

    I don't know at which releases it is enabled or disabled, but testing using a single thread really could give unexpected results.

    ReplyDelete
  2. This is true, I would be interested in what anyone else has found. I intend to run the same test with multiple threads.

    ReplyDelete
  3. Hi..Thanx for your suggestion on my blog: http://javaj2eeplanet.blogspot.com

    -ReDs
    http://funkyxone.blogspot.com

    ReplyDelete

Post a Comment

Popular posts from this blog

Java is Very Fast, If You Don’t Create Many Objects

System wide unique nanosecond timestamps

Comparing Approaches to Durability in Low Latency Messaging Queues