开发者

synchronize access to a static field

in Item 67 of Effective Java by Josh Bl开发者_运维知识库och, he mentioned that if a method modifies a static field, you must synchronize access to this field, as it's not possible for clients to perform external synchronization on such a method. I don't quite understand how come a client cannot perform external synchronization on a static method?

internal synchronization implementation:

public class Serial {
  private static int serialNumber = 0;

  public synchronized static void incSerial() {  
      serialNumber++;
  }

}

if no internal synchronization implemented, a client can synchronize externally:

synchronize(Serial.class) {

  Serial.incSerial();
}

any ideas?


A client can do that, but you can't force such a synchronization. So some client might do an unsynchronized access, and break everything.


You need to make sure that you use the lock associated with the class that holds the static instance variable. If you acquire it with a synchronized block before and then call the static method, it's fine. But you cannot enforce this on the client's code. They might forget or not be aware that the particular static variable is also used by other threads. So enforcing it, like Bozho suggested, by synchronizing the static method and making the instance variable private would be the best approach.

Tiberiu

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜