Access static variable in synchronized block

╄→尐↘猪︶ㄣ 提交于 2019-12-12 05:11:16

问题


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


来源:https://stackoverflow.com/questions/16263888/access-static-variable-in-synchronized-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!