The volatile modifier in Java is a special mechanism for ensuring the interaction between different threads. When One thread modifies a volatile variable, another thread can see the change. The first thread notifies the second thread that a variable has been modified.
This is explained in the following diagram:
Ready is a volatile Boolean variable with the initial value set to False. Answer is a non-volatile int variable with an initial value of 0.
The first thread prepares to modify the ready variable, which is the sender of two threads of communication. The second thread reads the ready variable, gets the value modified by the first thread, and therefore it is the receiver. When thread 1 modifies the ready variable in two threads, all variables in memory are visible to thread 1, and thread 2 is prepared to read the value of the prepare variable to true, all variables in memory must be visible to threads 2.
This ensures that if a thread is to output something, it is 42.
If ready is not volatile, what will happen? There will be no noticeable communication between thread 1 and Threads 2.
Thread 1 modifies the value after ready (now Non-volatile) may be passed to thread 2, so the thread may be able to read the value of ready to true. However, thread 1 may not pass the modified ready value to thread 2,answer's value or to thread 2, then thread 2 will output 0.
Resources:
Http://jeremymanson.blogspot.jp/2008/11/what-volatile-means-in-java.html
What does volatile in Java mean