I just learned about the volatile
keyword in Java.
Essentially it seems that if a variable is read from or written to in one CPU, then it is saved in that CPU's cache but not necessarily immediately written to memory.
In some cases I pass an object reference or primitive variable to another thread, but I have not used the volatile
keyword because I didn't know about that keyword until now.
I believe that if a new Thread reads that variable for the first time there is no issue. However, if my understanding is correct, then if a second thread changes the variable, then the first Thread's CPU may have it in cache and report an out of date value. Is this a true understanding of the effects of omitting the volatile
keyword?
Example:
- Thread A sets an object's variable value to
"First"
. - Thread B reads the value of that variable for the first time ever.
- Thread A changes the value to
"Second"
. - Thread B reads the value again shortly thereafter, but it still reports
"First"
because of CPU cache.
Is this the main consequence of omitting a volatile
keyword when it is necessary? Thread reporting an out of date value?
Is my understanding here correct? Also I am open to any other suggestions about when it is NOT necessary to use the volatile
keyword for a non-final variable that is accessed by another thread. I know when to use it, but I need to have a good understanding about when not to.