How to synchronize a static variable among threads running different instances of a class in Java?

JavaMultithreadingSynchronizationClassObject

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

There are several ways to synchronize access to a static variable.

  1. 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++;
         }
     } 
    
  2. Explicitly synchronize on the class object.

     public class Test {
         private static int count = 0;
    
         public void incrementCount() {
             synchronized (Test.class) {
                 count++;
             }
         }
     } 
    
  3. 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.

Solution 2 - Java

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();
    }  
}

Solution 3 - Java

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.

Solution 4 - Java

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();
    }  
}

Solution 5 - Java

You can synchronize your code over the class. That would be simplest.

   public class Test  
    {  
       private static int count = 0;  
       private static final Object lock= new Object();    
       public synchronized void foo() 
      {  
          synchronized(Test.class)
         {  
             count++;  
         }  
      }  
    }

Hope you find this answer useful.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnonymousView Question on Stackoverflow
Solution 1 - JavaDarronView Answer on Stackoverflow
Solution 2 - JavaKevinView Answer on Stackoverflow
Solution 3 - JavarichsView Answer on Stackoverflow
Solution 4 - JavaSunilView Answer on Stackoverflow
Solution 5 - JavaJafar AliView Answer on Stackoverflow