Java volatile Keyword
Example
Create a volatile
attribute:
public class Main {
public static volatile int x = 5;
public static void main(String[] args) {
System.out.println(x);
}
}
Definition and Usage
The volatile
keyword is a modifier that ensures that an attribute's value is
always the same when read from all threads.
Ordinarily the value of an attribute may be written into a thread's local cache and not updated in the main
memory for some amount of time. In this case, other threads will see a different value for the attribute. The
volatile
keyword makes sure that threads always update the value of an
attribute in main memory.
Related Pages
Read more about modifiers in our Java Modifiers Tutorial.