|
The volatile modifier is applicable only to the member variables. It is used while working with multiple threads. You need to understand how Java threads work to truly understand the use of volatile variable. Threads will be covered in Chapter 10. Nevertheless we will discuss what you must know about volatile in short.
For now, think of a thread as an execution context in which a Java program is running. In a multi-threaded application, multiple threads are executing, each in different context. If such threads are sharing data, you need to make sure of the integrity[******] of the shared data. Java provides two mechanisms to control the access to shared data variables, synchronization and the volatile variables. In synchronization, it is made sure that only one thread will access the shared data (and also the shared code).
Now let us see how the volatile keyword helps in controlling the access to shared data variable. Note that every thread keeps a private copy of variables. When you declare the shared variables as volatile, there is also a master copy of such variable. Now every thread needs to reconcile its private copy of that variable with the master copy whenever it accesses that variable. Thus, volatile variables are always in-sync among all threads that are sharing them.
As you can imagine, volatile member variable can be slower to access than non-volatile member variables due to this reconciliation at each access. But they are useful to avoid concurrency problems whenever synchronization is not an option. Use of volatile variables is rare but may be necessary in particular applications. They are typically used in multiprocessor environments and JIT compilers, but you will rarely find them useful in application programming.