In the sample code
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++;
}
}
}
on this page,
lock1 and lock2 are controlling the updates on c1 and c2 resply.
However,
synchronized(lock2)
is acquiring the lock of the object lock1 and releasing it when the synchronized block
synchronized(lock1) {
c1++;
}
is executed.
While this block is being executed, there may be an update on member c1 of this object still-- and I don't see how this update is being prevented by synchronizing on lock1 as in the code.
It is the object lock1 that there is exclusive access on-- and nothing else(?)
So, how is the implementation
public void inc1() {
synchronized(lock1) {
c1++;
}
}
in the above code different from
public void synchronized inc1() {
c1++;
}
or even
public void inc1() {
synchronized(c1) {
//do something on c1
}
}
when c1 is an object but not a primitive?
What am I missing here ?
Note: I saw
What is the difference between synchronized on lockObject and using this as the lock?
and
Java synchronized method lock on object, or method?
among some other discussions.