Java Synchronization Benchmark
Here is a very simple and straightforward benchmark to demonstrate how synchronization in Java can affect speed of execution to different extents in Java 1.4 and Java 6.
In the attached image (click above for full size), you can see that for Java 1.4 the synchronized method needs over 700% more time to do its work compared to the non-synchronized method. But for Java 6, the difference is lower with the synchronized method needing only 500% more time to do its work compared to the non-synchronized method.
Remember, JVMs, especially newer ones do some nifty run-time optimizations that most developers are not aware of at all – like “biased locking”. This feature reduces the time taken for reacquiring a lock if the same thread is taking the lock repeatedly. There are other features like “adaptive spinning” and “lock coarsening” as well. Of course, the fact is that it might just be other optimizations that are at work here instead.
Such a simple benchmark does not deserve to have any conclusions drawn from it. In fact, the effect may have been greatly amplified here because the program does only an increment within the function so locking becomes the bottleneck. Such a situation may of course be true in “real world” programs as well. But quite often, it is not.
I obtained this result on the single core 2.8Ghz PIV system at my desk at work.
Ideally, one should be using a multi-processor machine and multiple threads to demonstrate such effects. I would expect Java 5 to show results between those for 1.4 and 6.
Related posts:
- Blocked thread with Read Write Lock due to writer starvation
- Using -Xss to adjust Java default thread stack size to save memory and prevent StackOverflowError
- There is a difference between free space and usable space!
- Configuring Eclipse to use a JDK at a location with spaces in it
- ConcurrentHashSet in Java from ConcurrentHashMap
Tags: Benchmark, Code, Java, JVM, Lock, Optimization, Speed, Synchronization, Threads, Tips


Good one mate.You r a fundu techie.I appreciate ur enthu.Do u work in India or US?
@Zafin
As of now, at Pune in India.
The above results may or may not be too reliable, as you have not taken into account the JVM Hotspot, which must “warm up” before it kicks in.
@Blake
I agree, I agree. It is meant to be a simple example for a beginner.
400% more? Where do you get that from? 1328-219=1109, 1109/219=5.06. That’s 500%, not 400%.
@Bob
You are right. Thanks for catching that. Will update the post.
[...] Read the complete article Share and Enjoy: [...]