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.

Java Synchronization Benchmark

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.



Tags: , , , , , , , , ,
This entry was posted on Friday, February 1st, 2008 at 10:47 am and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

7 Responses to “Java Synchronization Benchmark”

  1. Zafin Linda

    Good one mate.You r a fundu techie.I appreciate ur enthu.Do u work in India or US?

  2. Onkar Joshi

    @Zafin
    🙂

    As of now, at Pune in India.

  3. Blake

    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.

  4. Onkar Joshi

    @Blake
    I agree, I agree. It is meant to be a simple example for a beginner.

  5. Bob Bobson

    400% more? Where do you get that from? 1328-219=1109, 1109/219=5.06. That’s 500%, not 400%.

  6. Onkar Joshi

    @Bob
    You are right. Thanks for catching that. Will update the post.

  7. Java Synchronization Benchmark

    […] Read the complete article Share and Enjoy: […]