The volatile modifier is used during declarations to specify that the variable is volatile. I don't know what you mean by "example" here, as the concept is ridiculously simple. Nothing to show here, just put the volatile keyword before instance and static variables that you want to be volatile.
Volatile variables have a few properties. Of which, the main ones are...
* Atomic access. Most variables are atomic during load and store, but with atomic they are guaranteed that the long and double are atomic too (using an internal JVM lock to accomplish this).
* No caching in registers. All read access are loaded directly from memory. All writes are flush directory to memory.
* Different ordering optimization. Or more correctly, the optimizer will try not to do code motion around volatile variables that can affect its behavior with other variables.
Mansukhdeep Thind wrote:Hi all
Can someone explain what exactly is the job of the volatile type modifier with a simple example?
The best use of volatile is visible in multi-threaded environment. Volatile, as Henry Wong said, are declared to be volatile while being access by multi-thread. There are two explanation to this now. One for Java 1.4 and second for Java 1.5.
Java 1.5 changed the definition of Volatile a little and internal implementation as well.