开发者

Synchronization on "reference" or on instance

开发者 https://www.devze.com 2022-12-14 10:44 出处:网络
Consider the following code: public class Foo { private static fina开发者_如何学Cl Object LOCK = new Object();

Consider the following code:

public class Foo {
  private static fina开发者_如何学Cl 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...


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号