Reputation: 89
(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.
Upvotes: 0
Views: 4035
Reputation: 49402
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++;
}
}
}
Upvotes: 4