How to synchronize a static variable among threads running different instances of a class in Java?
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.
If you're simply sharing a counter, consider using an AtomicInteger or another suitable class from the java.util.concurrent.atomic package:
public class Test {
private final static AtomicInteger count = new AtomicInteger(0);
public void foo() {
count.incrementAndGet();
}
}
Yes it is true.
If you create two instance of your class
Test t1 = new Test();
Test t2 = new Test();
Then t1.foo and t2.foo both synchronize on the same static object and hence block each other.
We can also use ReentrantLock to achieve the synchronization for static variables.
public class Test {
private static int count = 0;
private static final ReentrantLock reentrantLock = new ReentrantLock();
public void foo() {
reentrantLock.lock();
count = count + 1;
reentrantLock.unlock();
}
}