I came across a doc which stated that the usage of "volatile" fields in a class maintains sequential consistency of values.
I have not used volatile much in my coding and so could you give me a brief description about the appropriate usage and uses of using it.
Also please give me hint of how out JIT compilers have implemented the volatile keywords usage.
Volatile keyword is important because sometimes JVM caches the value of a variable for performance. In a multi-threaded system this can be a problem as a value set by one thread might not be visible to other threads for some time. If you don't want the JVM to cache the value of the variable, then you can make it volatile...
The volatile keyword simply tells the program that intermediary results of calculations on the volatile variable should not be cached.
Normally a program might leave a value in the processor register or in the memory cache or something like this, and only write it back to main memory at unknown points in time. This is fine for sequential execution, but if multiple threads try to access such a variable in memory, they might be accessing an old version of the variable, while the most current version is still in a register or in the cache.
Making a variable volatile prevents this. After every operation on it, its value gets written back to main memory. This is slower, but ensures that every thread is looking at the same value when they inspect a variable.
If a variable is edited and read by multiple threads, and access is restricted by synchronized blocks, then you don't have to worry about using volatile. When a thread enters a synchronized block, operations on that variable will be cached as they normally are, and as soon as the thread leaves the synchronized block, the final value in the cache is automatically written back to memory.
So in conclusion, you only have to use volatile if multiple threads access a variable, and the variable isn't protected by a synchronized block.
The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.