Hi
we want to know the use of volatile variable in java
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Satyapriya NayakPosted May 31, 2012, 6:16 AM
Java Memory model defines the possible rules for threads and the expected behavior of multi-threaded programs so that programmers can design their programs accordingly. JSR-133 describes the semantics of threads, locks, volatile variables and data races.
Volatile variables are treated different from other variables. When you mark a variable as volatile, this warns the compiler to get fresh copies of the variable rather than caching the variable in the registers.
Volatile variables can be used to store shared variables at a lower cost than that of synchronization, but they have limitations. While writes to volatile variables are guaranteed to be immediately visible to other threads (because JVM does not allow threads to cache volatile variables), there is no way to render a read-modify-write sequence of operations atomic, meaning, for example, that a volatile variable cannot be used to reliably implement a mutex (mutual exclusion lock) or a counter.
Please refer the below links
http://ilkinbalkanay.blogspot.in/2007/10/volatile-variables-in-java.html
http://www.javamex.com/tutorials/synchronization_volatile.shtml
http://en.wikipedia.org/wiki/Volatile_variable
http://www.cs.princeton.edu/courses/archive/spr96/cs333/java/tutorial/java/javaOO/volatile.html
Thanks
Chintan RathodPosted May 31, 2012, 6:05 AM
Volatile keyword
The volatile is a keyword defined in the java programming language. Keywords are basically reserved words which have specific meaning relevant to a compiler in java programming language likewise the volatile keyword indicates the following :
-- The volatile keyword is mostly used to indicate that a member variable of a class may get modified asynchronously by more than one thread.
-- This thing is noticeable that the volatile keyword is not implemented in many Java Virtual Machines.
-- The volatile keyword from the side of compiler tries to guarantee that all the threads should see the same value of a specified variable.
Generally speaking, the volatile keyword is intended to prevent the compiler from applying any optimizations on the code that assume values of variables cannot change "on their own."
Example,
public class Test
{
volatile int sharableValue;
}
Thanks & Regards
----------------
Chintan Rathod