I was reading on official tutorial on multithreading from oracle and I came cross this example (assuming c1
and c2
are never used together):
public class MsLunch {
private long c1 = 0;
private long c2 = 0;
private Object lock1 = new Object();
private Object lock2 = new Object();
public void inc1() {
synchronized(lock1) {
c1++;
}
}
public void inc2() {
synchronized(lock2) {
c2++;
}
}
}
}
It is said that by using lock 1 & lock 2, it helps to reduce unnecessary blocking as compare to using the word this in the synchronized block.
However, I don't really see how this helps to reduce blocking as they have no dependency on each other. I have multiple threads each running these two methods at the same time and the performance is rather similar when I use the lock objects and this keyword.
Can someone help to explain my confusion here? Love to see the explanation with an example to illustrate the difference clearly.
Adding on to the discussion here, this post helped to clarify my doubts as well. Key point: Putting synchronized on a method means the thread has to acquire the lock on the object instance before entering that method