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?