Possibly similar question:
http://stackoverflow.com/questions/106591/
Today I was debugging my game; It had a very difficult threading problem that would show up every few minutes, but was difficult to reproduce. So first I added the
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?