I’m testing out a code where I have 2 methods and a statement in each method is synchronized.
private final Object obj1 = new Object();
private final Object obj2 = new Object();
public void method1(int result)
{
//there's a loop to create delay
synchronized (obj1){
sum = sum + result;
}
//there's a loop to create delay
}
public void method2(int result)
{
//there's a loop to create delay
synchronized (obj2){
sum = sum - result;
}
//there's a loop to create delay
}
What I’m basically doing is I add a result to sum then subtract the same amount then print the sum. So my initial and final amount should be constant.
The problem is I don’t know why the final amount is not the same as initial amount when I use 2 diff objects as lock. HOWEVER it’s constant when I use ‘this’ object as lock for both statements. But using ‘this’ as object didn’t make execution time faster than using method synchronized.
I’m still new to synchronization concept so any help is appreciated.
When you specify an object in the
synchronizeblock, that object is used like a lock for that block: only onesynchronizeblock can use a lock object at any time.When you use two different objects as locks, they become two different locks: two threads can lock them both at the same time – one thread per lock. This explains the inconsistent results: two threads can grab two separate locks concurrently, and modify the
sumconcurrently, resulting in incorrect calculations.You should use a single lock to protect a single resource from concurrent access. This is what happens when you use
this; the same would happen if you usedobj1orobj2in bothsynchronizeblocks, except in this case a user of your object would not be able to cause your methods to block forever by synchronizing on your object, and intentionally not releasing the lock.