Fastest way to lock/synchronize objects.


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.


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.


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


  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.

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

  3. Hi..Thanx for your suggestion on my blog:



Post a Comment

Popular posts from this blog

Low Latency Microservices, A Retrospective

Unusual Java: StackTrace Extends Throwable

System wide unique nanosecond timestamps