1

I have seen usage of synchronized block by this so far but recently I learned that using dummy object is preferable. I found the following topic related to this.

Java synchronized method lock on object, or method?

As a summary, in the code below, two different object can not run addA and addB concurrently as both uses this for lock.

private int a;
private int b;

public synchronized void addA(){
    a++;
}

public synchronized void addB(){
    b++;
}

I am confused if I use dummy object for lock, what will be different if I use the line below in both method to synchronize? Because still they would have same lock.

synchronized(dummyObject){
    ...
}

So what it means that I should have two different dummy object for each method to use with sycnhronized as?

 public void addA(){
    synchronized(dummyObj1){
       a++;
    }
}

public void addB(){
    synchronized(dummyObj2){
       b++;
    }
}
Community
  • 1
  • 1
cincin
  • 67
  • 1
  • 7

2 Answers2

2

That is exactly the point of lock objects - you can use different locks for different operations. Assuming it makes sense to run addA and addB concurrently (and from the looks of it - it definitely does), you should indeed have two separate locks, one for each method.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

You are correct. In this case you need two different objects to synchronize on them separately.

For locking purpose the easiest way is to create Object objects.

Object lock1 = new Object();
Object lock2 = new Object();
Jakub H
  • 2,130
  • 9
  • 16
  • but what happen if I change lock1 object reference inside of the synchronized? – cincin Jan 06 '17 at 13:25
  • why would you change lock1 object reference? to make sure it is not possible to change those references (as it doesn't make sense to change them) you can add final modifier while declaring those objects. – Jakub H Jan 06 '17 at 13:28