In Java programming language the keyword volatile is used when you are working with multiple threads. The variable declared as volatile specifies that the variable is modified asynchronously by concurrently running threads. This instructs to the compiler to fetch them fresh each time, rather than caching them in registers. Threads that access shared variables to keep private working copies of the variables; in order to implement the multiple threads more efficiently. This also holds back certain optimizations that supposes no other thread will change the values unexpectedly. Since other threads can't see local variables therefore there is no need make the local variables as volatile.
You should prefer to use volatile variables rather than locks for one of two principal reasons: simplicity or scalability. Use of volatile variables instead of locks makes it easier to code and read. In addition, volatile variables cannot block a thread while the locks can do, therefore volatile variables are likely to cause scalability problems.
If you enjoyed this post then why not add us on Google+? Add us to your Circles
Liked it! Share this Tutorial
Post your Comment