Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

synchronize access to a static field

in Item 67 of Effective Java by Josh Bloch, 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?

like image 208
Sean Avatar asked Sep 04 '11 20:09

Sean


1 Answers

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

like image 87
Bozho Avatar answered Oct 12 '22 19:10

Bozho