You synchronize on a specific object, both a specific static lock object and a class object (what happens when static methods are declared synchronized):
class X { private static final Object lock = new Object(); public void oneAtATime() { synchronized (lock) { // Do stuff } } } class Y { public void oneAtATime() { synchronized (Y.class) { // Do stuff } } }
Each option has its pros and cons; locking on a class allows another code, outside the class, to use the same lock for its own reasons (which allows it to organize higher-level synchronization than what you provide), while the static final Object lock approach allows you to disable it by creating the lock field is closed (which simplifies the argument about locking and avoids locking your code because someone wrote bad code).
Of course, you can also use some synchronization mechanism from java.util.concurrent , such as explicit Lock s, which provide more control over the lock (and ReentrantLock currently performs slightly better than implicit locks under a high level of competition).
Edit: Please note that static / global locks are not a great way - this means that every instance of a class ever created will essentially be bound to all other instances (which, in addition to creating it is more difficult to check or read the code, can seriously damage scalability). I assume that you are doing this to synchronize some kind of global state? In this case, I would consider transferring this global / static state to a class and implement synchronization for each instance, not globally.
Instead of this:
class Z { private static int state; public void oneAtATime(){ synchronized (Z.class) { state++; } } }
Do it like this:
class State { private int value; public synchronized void mutate(){ value++; } } class Z { private final State state; public Z(State state){ this.state = state; } public void oneAtATime(){ state.mutate(); } } // Usage: State s1 = new State(), s2 = new State(); Z foo = new Z(s1); Z bar = new Z(s1); Z frob = new Z(s2); Z quux = new Z(s2);
Now foo and bar are still connected to each other, but they can work independently of frob and quux .
gustafc
source share