I have 2 methods, one is static and another one is non static and both are synchronized. So both the methods can execute concurrently by two threads as one thread can use object lock to enter non static syn method and another one can use Class lock to enter static synchronized method. Suppose if i have a static variable, then both the thread can access this variable at the same time. So there will be a race condition. How can we restrict the access to this?
Just assume that the static variable is an primitive int. Below is the program demonstrates the issue.
Sometimes the output is
Method1:Thread Name :Thread-0 Counter:1
Method2:Thread Name :Thread-0 Counter:3
Method1:Thread Name :Thread-1 Counter:3
Method2:Thread Name :Thread-1 Counter:4
I want the counter should increase sequentially as the variable is static and only one copy of it get stored per JVM....The output clearly shows that there is an conflict in accessing the variable. Volatile doesnt work as it is only for instance variables not for static.
volatile works fine with static, but I forgot it doesn't do much in the way of race conditions. Yes, the only way is to use a common lock:
Which reminds me. Rob Spoor's solutions shouldn't work in general, because subclasses may return a different class object when getClass() is being called. Static methods can't even use the getClass() method. Always use class literals (Classname.class).