(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.
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++; } } }
Synchronized Static method.
public class SomeClass { private static int sum = 0; public static synchronized void increaseSum() { sum++; } }
Synchronize on class object
public class SomeClass { private static int sum= 0; public void increaseSum() { synchronized (SomeClass .class) { sum++; } } }