简体   繁体   中英

Access static variable in synchronized block

(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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM