What the keyword volatile means in Java?
What means?
Means that your thread always will work with memory values instead of local copies.
When should I apply?
As said before, only and only use volatile for attributes, you can want the behavior for methods and blocks, you should use synchronized.
What is the behavior?
The behavior as the Java documentation says is:
Using volatile
variables reduces the risk of memory consistency errors, because any write to a volatile
variable establishes a happens-before relationship with subsequent reads of that same variable. This means that changes to a volatile
variable are always visible to other threads. What's more, it also means that when a thread reads a volatile
variable, it sees not just the latest change to the volatile
, but also the side effects of the code that led up the change.
The image bellow illustrate this behavior.
This is for multithreading environment and in this context, the thread always will work with memory value not with your own.
Example of declaration into a multithreading environment. This code only show the declaration.
Thank you for your time :)