Tuesday, July 23, 2013

Threads: All About Volatile

I was thinking to improve my threading fundamentals, so I planned to make few notes for myself that will assist me in future (Obviously at the time of Interviews). Following questions and answers have been taken from stackoverflow.com. This post is a sticky notes post for me. Please do not use the answers for reference purpose.

Here we will try to concentrate on basic questions on volatile. Volatile has been quite a common word in threading world, but it has not been utilized so much in codes. Let’s start digging little deeper to figure out about volatile.


Most of the information has been taken from https://www.ibm.com/developerworks/java/library/j-jtp06197/. I have tried to get the extract of the article.

Volatile variables can perform subset of things that synchronize block can perform. In general cases, lock offers mutual exclusion and visibility feature. Mutual exclusion facilitated only one thread to access the shared resources, whereas visibility means that inconsistent data must not be visible across different threads. Volatile variables can only provide visibility feature to the application.
If a variable is declared volatile, so any thread reading the variable will always see the most updated value of the variable.
Java 5 onward, to access a volatile variable JVM creates a memory barrier and synchronize the main memory will all cached instances, and returns latest and most updated information.

Volatile variables must be used where their assignment do not depend on previous value.

volVar += 1; //It is not a correct use to volatile variables.

That’s why volatile variables cannot be used as counters.
Volatile variables are preferred over Synchronized blocks due to Simplicity, No need to write lot of code, and scalability, no locks are held while processing, but volatile has got its own restrictions as well.

You can use volatile variables instead of locks only under a restricted set of circumstances. Both of the following criteria must be met for volatile variables to provide the desired thread-safety:
  • Writes to the variable do not depend on its current value.
  • The variable does not participate in invariant with other variables.
Though people discourage to use to volatile variables, but still there are few well defined patterns to use volatile variables.

In Producer/consumer problem we change the status of the flag so that other thread can enter in the critical section and can read or write the data. The access of the block is managed with a Boolean. This Boolean can be volatile variables.

volatile boolean stopRequested;
public void stop() { stopRequested = true; }
public void doWork() { 
    while (!stopRequested) { 
        // do stuff
    }
}
Now if you will see the transactions performed on volatile variables, then you will realize that volatile variable’s state was not considered while updating it. So this is the correct use of volatile variable.

Without synchronization, sometime it is possible to see updated object’s reference but stale data. It is quite a tricky problem, but it can be handled with volatile variable.
A key requirement for this pattern is that the object being published must either be thread-safe or effectively immutable (effectively immutable means that its state is never modified after its publication). The volatile reference may guarantee the visibility of the object in its as-published form, but if the state of the object is going to change after publication, then additional synchronization is required.
public class BackgroundFloobleLoader {
    public volatile Flooble theFlooble;

    public void initInBackground() {
        // do lots of stuff
        theFlooble = new Flooble();  // this is the only write to theFlooble
    }
}

public class SomeOtherClass {
    public void doWork() {
        while (true) { 
            // do some stuff...
            // use the Flooble, but only if it is ready
            if (floobleLoader.theFlooble != null) 
                doSomething(floobleLoader.theFlooble);
        }
    }
}
It is very similar to temperature reading. Temperature is read and written in the memory which can be accessed by multiple threads.

There are few more patterns listed in the article, but those patterns will need further understanding of java related technologies.

No comments:

Post a Comment