Thursday, November 17, 2016

Volatile in JAVA

Volatile keyword can be applied only to variables. It cannot be applied to class or method.

Volatile is used to indicate that a variable's value will be modified by different threads.

The value of volatile variable never get cached thread-locally; all reads and writes go straight to main memory.

A volatile variable can be used as an alternative way of to achieve synchronization in Java in some cases, like visibility. 

With volatile variable, it's guaranteed that all reader threads will see updated value of the volatile variable once write operation is completed, without volatile keyword different reader threads may see different values.

Example:
Imagine a situation in which two or more threads have access to a shared object which contains a counter variable declared like this:

public class SharedVariable {
    public int counter = 0;
}

Imagine too, that only Thread 1 increments the counter variable, but both Thread 1 and Thread 2 may read the counter variable from time to time.

If the counter variable is not declared volatile there is no guarantee about when the value of the counter variable is written from the CPU cache back to main memory. This means, that the counter variable value in the CPU cache may not be the same as in main memory.

The problem with threads not seeing the latest value of a variable because it has not yet been written back to main memory by another thread, is called visibility problem (updates of one thread are not visible to other threads).

By declaring the counter variable volatile all writes to the counter variable will be written back to main memory immediately. Also, all reads of the counter variable will be read directly from main memory. Here is how the volatile declaration of the counter variable looks:

public class SharedVariable {
    public volatile int counter = 0;
}

Declaring a variable volatile thus guarantees the visibility for other threads of writes to that variable.

No comments:

Post a Comment

Home