0

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 ?

Roman C
  • 49,761
  • 33
  • 66
  • 176
jayendra bhatt
  • 1,337
  • 2
  • 19
  • 41
  • Note also that using multiple lock objects in the instance methods of a single object can make deadlock easier. – Andy Thomas Sep 21 '14 at 20:42

1 Answers1

0

Either way is fine. There are design reasons to use your object as the lock, and there are design reasons to keep the lock private as you have done.

The only critisizm I would make is that Object typically gets used as a lock in Java, you don't have to invent a dummy class.

public class MsLunch {
    private long c1 = 0;
    private long c2 = 0;
    private final Object lock1 = new Object();
    private final Object lock2 = new Object();

    public void inc1() {
        synchronized(lock1) {
            c1++;
        }
    }

    public void inc2() {
        synchronized(lock2) {
            c2++;
        }
    }
}
markspace
  • 10,621
  • 3
  • 25
  • 39