views:

48

answers:

1

Consider the following code:

public class Foo {
  private static final Object LOCK = new Object();
  private Object _lockRef1 = LOCK;
  private Object _lockRef2 = LOCK;
  private int _indx = 0;

  public void dec() {
    synchronized(_lockRef1) {
      _indx--;
    }
  }

  public void inc() {
    synchronized(_lockRef2) {
      _indx++;
    }
  }
}

Is call to methods dec() and inc() threadsafe? On the one hand these methods are synchronized on two different instances _lockRef1 and _lockRef2. On the other hand, these instances "point" on the same object LOCK...

+3  A: 

They're not "synchronized on two different instances" - just because you use two different variables doesn't mean there are two different instances. You've got several variables each of which will have the same value - a reference to the single instance of java.lang.Object.

So yes, this is thread-safe. Of course you shouldn't write code like this in terms of readability, but assuming you're just trying to understand what happens, it's fine.

Jon Skeet
The question is tagged 'Java', so I think this would be `java.lang.Object`.
Yuval
@Yuval: Doh - didn't spot that. Thanks, fixed :)
Jon Skeet
Got it! Thanks! Actually, I have an emun instead of "private static final Object", but it seems the idea is the same.
Lopotun