Possibly similar question:
Do you ever use the volatile keyword in Java?
synchronized
keyword to each of my methods. That didn't work. Then I added the volatile
keyword to every field. The problem seemed to just fix itself.
After some experimentation I found that the field responsible was a GameState
object which kept track of my game's current state, which can be either playing or busy. When busy, the game ignores user input. What I had was a thread that constantly changed the state
variable, while the Event thread reads the state
variable. However, after one thread changes the variable, it takes several seconds for the other thread to recognize the changes, which ultimately causes the problem.
It was fixed by making the state variable volatile
.
Why aren't variables in Java volatile
by default and what's a reason not to use the volatile
keyword?
To make a long story short, volatile variables--be they in Java or C#--are never cached locally within the thread. This doesn't have much of an implication unless you're dealing with a multiprocessor/multicore CPU with threads executing on different cores, as they'd be looking at the same cache. When you declare a variable as volatile, all reads and writes come straight from and go straight to the actual main memory location; there's no cache involved. This has implications when it comes to optimization, and to do so unnecessarily (when most variables don't need to be volatile) would be inflicting a performance penalty (paltry as it may or may not be) for a relatively small gain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With