Thursday, 26 May 2011

Volatile keyword in java

Understanding volatile in java
To understand volatile, first you have to understand a little something about the Java memory model.
  • Each thread in Java takes place in a separate memory space, I mean its personal stack, but various threads share memory among them.
  • You need to use special mechanisms to guarantee that communication happens between these threads, as you would on a message passing system.
  • Memory writes that happen in one thread can "leak through" and be seen by another thread, but this is by no means guaranteed. Without explicit communication (i.e. using locks on the shared data), you can't guarantee which writes get seen by other threads, or even the order in which they get seen.
The Java volatile modifier guarantees that communication happens between threads. When one thread writes to a volatile variable, and another thread sees that write, the first thread is telling the second about all of the contents of memory up until it performed the write to that volatile variable. So if a variable is declared as volatile then is guaranteed that any thread which reads the field will see the most recently written value.

What is happens-before relation?
volatile’s job is to guarantee “happens-before” behavior. This means three things:
  1. Write operations are executed before read operations.
  2. Compilers are not allowed to re-order accesses to the field.
  3. Caches must be flushed before reading the field
Note
The keyword volatile will not perform any mutual exclusive lock on the variable. Most recent value is ensured because it ignores caching. So if a variable is declared volatile, it takes the value from the main memory, rather than cache and delivers the recent value or latest value.

As of Java 5 write access to a volatile variable will also update non-volatile variables which were modified by the same thread. This can also be used to update values within a reference variable, e.g. for a volatile variable person. In this case you must use a temporary variable person and use the setter to initialize the variable and then assign the temporary variable to the final variable. This will then make the address changes of this variable and the values visible to other threads.

Difference between volatile in old and new Java Memory Model
Pre-java 5, volatile had different meaning, but java developers changed its meaning. Lets look at the change:
Old java volatile New java volatile
A volatile variable cannot be cached. (same)
A volatile variable cannot be reordered with another variable but may be reordered with volatile variable. A volatile variable cannot be reordered. (notice the change)
Volatile observes happens-before-relationship.
See -

No comments:

Post a Comment