title: How to synchronize a static variable among threads running different instances of a class in Java?
body: <p>I know that using the <code>synchronize</code> keyword before a method brings synchronization to that object. That is, 2 threads running the same instance of the object will be synchronized.   </p>
  
  <p>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.  </p>
  
  <p>Can we achieve synchronization in the following way?  </p>
  
  <pre><code>public class Test  
  {  
     private static int count = 0;  
     private static final Object lock= new Object();    
     public synchronized void foo() 
    {  
        synchronized(lock)
       {  
           count++;  
       }  
    }  
  }
  </code></pre>
  
  <p>Is it true that since we have defined an object <code>lock</code> that is static and we are using the keyword <code>synchronized</code> for that lock, the static variable <code>count</code> is now synchronized across instances of class <code>Test</code>?</p>