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.
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
Version | bits | 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 7 | 64 | 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 |
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.
ReplyDeleteI don't know at which releases it is enabled or disabled, but testing using a single thread really could give unexpected results.
This is true, I would be interested in what anyone else has found. I intend to run the same test with multiple threads.
ReplyDeleteHi..Thanx for your suggestion on my blog: http://javaj2eeplanet.blogspot.com
ReplyDelete-ReDs
http://funkyxone.blogspot.com