I think this question must have been asked somewhere but when I look for it I unfortunately find only different topics. Anyway here is the code:
public class A {
Object lockX = new Object();
Object lockY = new Object();
Object lockZ = new Object();
int c1;
int c2;
public void foo1() {
synchronized(lockX) {
c1++;
}
}
public void bar1() {
synchronized(lockY) {
c1++;
}
}
public void foo2() {
synchronized(lockZ) {
c2++;
}
}
public void bar2() {
synchronized(this) {
c2++;
}
}
}
Basically foo1 and bar1 are incorrect. They use different lock to protect c1, so in fact c1 won't be protected and both those functions can run concurrently. My question however is about foo2 and bar2. Are they ok? They also use different locks but bar2 is locking whole object, so does it prevents modifing c2 concurrently?