Access static variable in synchronized block

2019-09-06 12:40发布

问题:

(Java synchronization problem)As my title, can I access a static variable in a synchronized block? Will it cause inconsistency ? Can anyone tell me the detail of the disadvantages or advantages of accessing a static variable synchronized block.

回答1:

can I access a static variable in a synchronized block ?

Yes, You can.

Will it cause inconsistency ?

Static means shared across all the instances of that Class in a JVM. Shared resources are not thread-safe.Hence Static variables are not thread safe.So, if multiple threads tries to access a static variable, it may result in inconsistency.

The ways, which I know of to synchronize access to a static variable.

  1. Synchronize on Static object.

       public class SomeClass{
          private static int sum = 0;
          private static final Object locker = new Object();
    
          public void increaseSum() {
               synchronized (locker) {
               sum++;
          }
        }
      }
    
  2. Synchronized Static method.

    public class SomeClass {
        private static int sum = 0;
    
       public static synchronized void increaseSum() {
         sum++;
     }
    }
    
  3. Synchronize on class object

     public class SomeClass {
        private static int sum= 0;
    
        public void increaseSum() {
           synchronized (SomeClass .class) {
           sum++;
         }
       }
     }