There are several ways to synchronize access to a static variable.
-
Use a synchronized static method. This synchronizes on the class object.
public class Test { private static int count = 0; public static synchronized void incrementCount() { count++; } }
-
Explicitly synchronize on the class object.
public class Test { private static int count = 0; public void incrementCount() { synchronized (Test.class) { count++; } } }
-
Synchronize on some other static object.
public class Test { private static int count = 0; private static final Object countLock = new Object(); public void incrementCount() { synchronized (countLock) { count++; } } }
Method 3 is the best in many cases because the lock object is not exposed outside of your class.