Say I have two threads and an object. One thread assigns the object:
public void assign(MyObject o) {
myObject = o;
}
Another thread uses t
I have spent quite a lot of time trying to understanding the volatile
keyword.
I think @aleroot has given the best and simplest example in the world.
This is in turn my explanation for dummies (like me :-)):
Scenario1: Assuming the stop
is not declared as volatile then
a given thread does and 'thinks' the following:
stopWork()
is called: I have to set the stop
to true
Scenario2: Now let the stop
be declared as volatile:
stopWork()
is called: I have to set the stop
to true
volatile
. I have to occupy CPU a bit longer...No synchronization, just a simple idea...
Why not to declare all variables volatile
just in case? Because of Scenario2/Step3. It is a bit inefficient but still better than regular synchronization.