in the below code snippet
public class MsLunch {
private long c1 = 0;
private long c2 = 0;
private Object lock1 = new Object();
// private Object lock2 = new Object();
private Dummy lock2 = new Dummy();
public void inc1() {
synchronized(lock1) {
c1++;
}
}
public void inc2() {
synchronized(lock2) {
c2++;
}
}
}
i have changed the lock object used to protect the c2 count. i have used a dummy class which is no where related to MsLunch class. Is it fine or should i always put the lock on the object of the current class("this" or MsLunch object or parent class Object). Please answer as i have been struggling a long way to understand the role of object used in synchronized block. Also is it necessary that the synchronized block member fields and variables must be held by the object used to lock ?