I know that using the synchronize
keyword before a method brings synchronization to that object. That is, 2 threads running the same instance of the object will be synchronized.
However, since the synchronization is at the object level, 2 threads running different instances of the object will not be synchronized. If we have a static variable in a Java class that is called by the method, we would like it to be synchronized across instances of the class. The two instances are running in 2 different threads.
Can we achieve synchronization in the following way?
public class Test
{
private static int count = 0;
private static final Object lock= new Object();
public synchronized void foo()
{
synchronized(lock)
{
count++;
}
}
}
Is it true that since we have defined an object lock
that is static and we are using the keyword synchronized
for that lock, the static variable count
is now synchronized across instances of class Test
?
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.