0

I am new to multithreading and wanted to test out performance of method vs. block level synchronization (expecting block level synchronization to have better performance).

My method level synchronization

 public synchronized void deposit (double amount) {

    //random calculations to put more load on cpu
    int k=0;
    for(int i=0; i<5 ;i++){
        k=(k+i)*10000;
    }
    this.balance = this.balance + amount;
}

vs my block level synchronization

 public void deposit (double amount) {

    //random calculations to put more load on cpu
    int k=0;
    for(int i=0; i<5 ;i++){
        k=(k+i)*10000;
    }
    synchronized (this) {
        this.balance = this.balance + amount;
    }
}

I was expecting the performance of the block level synchronization to be faster but it was actually slower. In a few runs the performance was the same but overall it ran 0.2 sec slower than the method level synchronization.

Why is it slower?

mouse_s
  • 58
  • 1
  • 9
  • 1
    How did you benchmark it? See ["How do I write a correct micro-benchmark in Java?"](https://stackoverflow.com/questions/504103) – yshavit Feb 01 '19 at 20:07
  • @yshavit I used stopwatch benchmarking. Looking at the reference you gave it seems like my test is insignificant since the result runs in less than 5 secs. Putting testing aside am I correct to assume that the block synchronization should perform better? – mouse_s Feb 01 '19 at 20:18
  • 1
    I would expect the block synchronization to be no slower. But it wouldn't surprise me if the JIT can unroll your loop and make the `k` calculation very quick (or even a const), in which case they should perform about the same. I think the problem with your benchmark is probably a combination of the test being very quick, the test not iterating, and JIT noise. A framework like JMH should be able to give you good results, so I'd encourage you to try that and see if you can reproduce this. It's not totally unreasonable that you've triggered an actual surprise in the JVM! – yshavit Feb 01 '19 at 20:30
  • 1
    You should not. Blocks and methods should perform about the same. More importantly, micro-optimizations like this are [always a bad idea.](http://wiki.c2.com/?PrematureOptimization) Use whatever makes sense for the logical design of the program. – markspace Feb 01 '19 at 20:36
  • It's not unlikely that the optimizers have eliminated the `k` loop from the running code altogether. – Lew Bloch Feb 01 '19 at 21:04

0 Answers0