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

5

131

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?

Retrospect answered 22/1, 2010 at 20:25 Comment(2)
all these answers are USELESS unless the lock object is declared FINAL!Sharronsharyl
Also look at java.util.concurrent.atomic.AtomicIntegerLatham
R
210

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.

Rabbinate answered 22/1, 2010 at 20:50 Comment(5)
1. the first one even don't need a lock object, shouldn't it be the best?Coronal
2. declare count as volatile would also works, as volatile makes sure the variable is synchronized.Coronal
The reason #3 is the best is that any random bit of code could synchronize on Test.class and potentially spoil your day. Also, class initialization runs with a lock on the class held, so if you've got crazy class initializers you can give yourself headaches. volatile doesn't help for count++ because it's a read / modify / write sequence. As noted in a different answer, java.util.concurrent.atomic.AtomicInteger is likely the right choice here.Become
Don't forget to synchronize the read operation on count if you want to read the correct value as set by other threads. Declaring it volatile (in addition to synchronized write) will also help with this.Windhover
@Ferrybig no, you are locking on Test.class . this would be the lock for synchronized non-static methodsJustis
F
65

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();
    }  
}
Fugere answered 22/1, 2010 at 20:46 Comment(1)
It is available in java 1.5, not in 1.6.Jarnagin
G
4

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.

Grano answered 22/1, 2010 at 20:44 Comment(1)
one will block the other, not each other at once if taken care.Izettaizhevsk
D
1

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();
    }  
}
Duroc answered 4/7, 2020 at 8:48 Comment(0)
I
0

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.

Izettaizhevsk answered 12/1, 2013 at 9:18 Comment(2)
This will work, but as mentioned elsewhere by @Fadden, beware that any other thread could also synchronize on Test.class and affect behaviour. This is why synchronizing on lock might be preferred.Lurdan
What you are saying is correct. That is why I clearly mention that the above is the simplest approach.Izettaizhevsk

© 2022 - 2024 — McMap. All rights reserved.