Friday, June 3, 2011

How to use Volatile keyword in JavaWhat is volatile variable in Java and when to use Volatile variable in Java is famous multi-threading interview question in Java interviews. Though many programmer knows what is a volatile variable but they fail on second part i.e. where to use volatile variable in Java as its not common to have clear understanding and hands-on on volatile in Java. In this tutorial we will address this gap by providing simple example of volatile variable in Java and discussing some when to use Volatile variable in Java. Any way Volatile keyword in Java is used as an indicator to Java compiler and Thread that do not cache value of this variable and always read it from main memory. So if you want to share any variable in which read and write operation is atomic by implementation e.g. read and write in int or boolean variable you can declare them as volatile variable. From Java 5 along with major changes like Autoboxing, Enum, Generics and Variable arguments , Java introduces some change in Java Memory Model (JMM), Which guarantees visibility of changes made by one thread to another also as "happens-before" which solves the problem of memory writes that happen in one thread can "leak through" and be seen by another thread. Java volatile keyword cannot be used with method or class and it can only be used with variable. Java volatile keyword also guarantees visibility and ordering , after Java 5 write to any volatile variable happens before any read into volatile variable. By the way use of volatile keyword also prevents compiler or JVM from reordering of code or moving away them from synchronization barrier.

If you look at the code carefully you will be able to figure out:1) We are only creating instance one time2) We are creating instance lazily at the time of first request comes.

If we do not make _instance variable volatile then Thread which is creating instance of Singleton is not able to communicate other thread, that instance has been created until it comes out of the Singleton block, so if Thread A is creating Singleton instance and just after creation lost the CPU, all other thread will not be able to see value of _instance as not null and they will believe its still null.

Why? because reader threads are not doing any locking and until writer thread comes out of synchronized block, memory will not be synchronized and value of _instance will not be updated in main memory. With Volatile keyword in Java this is handled by Java himself and such updates will be visible by all reader threads.

Let’s see another example of volatile keyword in Java

most of the time while writing game we use a variable bExit to check whether user has pressed exit button or not, value of this variable is updated in event thread and checked in game thread , So if we don't use volatile keyword with this variable , Game Thread might miss update from event handler thread if its not synchronized in java already. volatile keyword in java guarantees that value of volatile variable will always be read from main memory and "happens-before" relationship in Java Memory model will ensure that content of memory will be communicated to different threads.

In this code example One Thread (Game Thread) can cache the value of "bExit" instead of getting it from main memory every time and if in between any other thread (Event handler Thread) changes the value; it would not be visible to this thread. Making boolean variable "bExit" as volatile in java ensures this will not happen.

When to use Volatile variable in Java

One of the most important thing in learning of volatile keyword is understanding when to use volatile variable in Java. Many programmer knows what is volatile variable and How does it work but they never really used volatile for any practical purpose. Here are couple of example to demonstrate when to use Volatile keyword in Java:

1) You can use Volatile variable if you want to read and write long and double variable atomically. long and double both are 64 bit data type and by default writing of long and double is not atomic and platform dependence. Many platform perform write in long and double variable 2 step, writing 32 bit in each step, due to this its possible for a Thread to see 32 bit from two different write. You can avoid this issue by making long and double variable volatile in Java.

2) Volatile variable can be used as an alternative way of achieving synchronization in Java in some cases, like Visibility. with volatile variable its guaranteed that all reader thread will see updated value of volatile variable once write operation completed, without volatile keyword different reader thread may see different values.

3) volatile variable can be used to inform compiler that a particular field is subject to be accessed by multiple threads, which will prevent compiler from doing any reordering or any kind of optimization which is not desirable in multi-threaded environment. Without volatile variable compiler can re-order code, free to cache value of volatile variable instead of always reading from main memory. like following example without volatile variable may result in infinite loop

privatebooleanisActive=thread;publicvoidprintMessage(){while(isActive){System.out.println("Thread is Active");}}

without volatile modifier its not guaranteed that one Thread see the updated value of isActive from other thread. compiler is also free to cache value of isActive instead of reading it from main memory in every iteration. By making isActive a volatile variable you avoid these issue.

4) Another place where volatile variable can be used is to fixing double checked locking in Singleton pattern. As we discussed in Why should you use Enum as Singleton that double checked locking was broken in Java 1.4 environment.

Important points on Volatile keyword in Java

1. volatile keyword in Java is only application to variable and using volatile keyword with class and method is illegal.

2. volatile keyword in Java guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache.

3. In Java reads and writes are atomic for all variables declared using Java volatile keyword (including long and double variables).

4. Using Volatile keyword in Java on variables reduces the risk of memory consistency errors, because any write to a volatile variable in Java establishes a happens-before relationship with subsequent reads of that same variable.

5. From Java 5 changes to a volatile variable are always visible to other threads. What’s more it also means that when a thread reads a volatile variable in Java, it sees not just the latest change to the volatile variable but also the side effects of the code that led up the change.

6. Reads and writes are atomic for reference variables are for most primitive variables (all types except long and double) even without use of volatile keyword in Java.

7. An access to a volatile variable in Java never has chance to block, since we are only doing a simple read or write, so unlike a synchronized block we will never hold on to any lock or wait for any lock.

8. Java volatile variable that is an object reference may be null.

9. Java volatile keyword doesn't means atomic, its common misconception that after declaring volatile ++ will be atomic, to make the operation atomic you still need to ensure exclusive access using synchronized method or block in Java.

10. If a variable is not shared between multiple threads no need to use volatile keyword with that variable.

Difference between synchronized and volatile keyword in Java

What is difference between volatile and synchronized is another popular core Java question asked in multi-threading and concurrency interviews. Remember volatile is not a replacement of synchronized keyword but can be used as an alternative in certain cases. Here are few differences between volatile and synchronized keyword in Java.

1. Volatile keyword in Java is a field modifier, while synchronized modifies code blocks and methods.

5. Since volatile keyword in Java only synchronizes the value of one variable between Thread memory and "main" memory while synchronized synchronizes the value of all variable between thread memory and "main" memory and locks and releases a monitor to boot. Due to this reason synchronized keyword in Java is likely to have more overhead than volatile.

6. You can not synchronize on null object but your volatile variable in java could be null.

7. From Java 5 Writing into a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire

In Summary volatile keyword in Java is not a replacement of synchronized block or method but in some situation is very handy and can save performance overhead which comes with use of synchronization in Java

if you like to know more about volatile I would also suggest to go thorough FAQ on Java Memory Model here which explains happens-before operations quite well.

Hi Anonymous, Volatile and Synchronized are completely different with each other. you can not use volatile keyword with methods while synchronized keyword can be used. similarly synchronized keyword can not be applied to variable while you can make variable volatile. to read more about synchronized read my post How Synchronization works in Java

So to me it only makes sense using VOLATILE with a static field, is this assumption right?As in Aban example, there is no need for testValue and ready being volatile because each instance of thread would have its own version of these fields, it's not shared between them.

Hi Chris, Thanks for your comment. double check lock example will not work prior to Java5 but with change in Java memory model and guarantee provided by volatile keyword in Java , double checked locking will work if we make Singleton instance volatile. as I have mentioned in point 5 "From Java 5 changes to a volatile variable are always visible to other threads"

As others have pointed out this blog is misleading. Volatile in your example has nothing to do with ensuring the field is non-null (this guarantee would actually cause a problem in the original Java memory model - see link below).

As I found this blog by googling "java volatile" people are probably reading it and getting incorrect information.

The example you provided requires a volatile because the reading of a volatile (assuming later Java memory model) guarantees that a previous write to the volatile has completed, and this in turn guarantees the object was constructed completely because of "as-if-serial" preservation and its rules regarding volatile. Without a volatile, _instance could be written to in a thread and "leaked" out of its local memory into another thread before the object is constructed fully, because "as-if-serial" rules in that case would allow reordering within the thread as long as that thread isn't affected.

You should read this and re-write the blog (or just link to this page which explains it anyway):http://www.ibm.com/developerworks/library/j-jtp03304/

my question is:in your double locking example, if using volatile, do we still need to use synchronised block? it sounds like when thread A is calling 'getInstance()' for the first time, it will have the right to create the _instance obj. if other threads are trying to call getInstance(), they will find out A is modifying _instance and need to wait for thread A until it finishes the instantiation. Is that right?

@Anonymous, yes, you need to use synchronized block to ensure that multiple instance of same object is not created. By making singleton instance volatile, you are ensuring that you don't see half backed object, this was the problem before Java introduces memory model and happens before rule. As per happens-before rule, Write to volatile variable happens before every subsequent read of that volatile variable.

No, that's right and you don't need to use volatile keyword along with synchronized, they are for different purpose. volatile variable offers happens before guarantee that any write on volatile variable happens before subsequent read on that variable. It's different than synchronized keyword because it's doesn't provide mutual exclusion, and only gives visibility and ordering guarantee.

- In the case of double checked locking in Singleton patten.What is the need to declare a variable volatile, if the synchronized keyword takes care of synchronizing the value of all variable between thread memory and "main memory" ?

Read more: http://javarevisited.blogspot.com/2011/06/volatile-keyword-java-example-tutorial.html#ixzz2UEwqgU1g Ok. In such case, lets tak what is the need of declaring

That's a good question Anonymous. If you look at code for double checked locking, you will see that first check is done outside synchronized block i.e. without any synchronization, which means, while one thread is initializing variable inside synchronized block, other thread can see half initialized Singleton instance, because first check is without any guarantee. By making _instance variable volatile, you ensure that write happens before read, which means when another thread reads _instance value, it won't see half initialized object. Hope this clears your doubt.

In one of the interview, I was asked that can we make an array volatile in Java? and they further grilled me on this i.e. will reading elements from array is volatile operation or not, what are the volatile read in case of array etc. I managed to answer that, because we can definitely make any array volatile but only assignment to array reference variable is volatile write e.g.

private volatile int[] numbers = new int[10];

is a volatile read operation and guarantees happens before relationship, but changing individual index is not a volatile write operation.

The volatile modifier tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of your program. One of these situations involves multithreaded programs. In a multithreaded program, sometimes two or more threads share the same variable. For efficiency considerations, each thread can keep its own, private copy of such a shared variable

HI javin, for volatile test, is it necessary to mark volatile of data type int?i attend 1 interview they asked me i have int variable, how to make thread safe? i told all the varaible data type are atomic operation except long & double, so no need to mark as volatile. interviewer told its wrong, for thread safe we need to mark as volatile. i m getng confused.

This post is excellent for learning what is volatile and their application. Really appreciate Javin. Sadly, it does not justify the heading given. It never explore how it works. Some newbie may get confused with the statement "reading the master copy". In a sense how volatile is different from static. Static works in same fashion. If possible please explain how it works in java and whats the internal difference.

The article is great. However I got confused with what you mentioned in two places(3 and 9) which seems(to me) opposite of each other.Could you make it bit more clear

3. In Java reads and writes are atomic for all variables declared using Java volatile keyword (including long and double variables).

9. Java volatile keyword doesn't means atomic, its common misconception that after declaring volatile ++ will be atomic, to make the operation atomic you still need to ensure exclusive access using synchronized method or block in Java.

I am probably still missing some point regarding Singleton with volatile. I do understand the purpose of volatile and its effect there but I am not convinced that without volatile it is broken.Please correct me if I am wrong. If volatile is not present and thread A enters synchronized block and looses a cpu just after a creation of a instance. Ok thread B still see a _instance null which means it waits to acquire a monitor before creating an instance.When tread A exits sync block it propagates all variables to main memory, when thread B acquire a lock it synchronize its variables so gets updated _instance. That doesn't fulfill the condition, no instance creation. I see there possible performance penalty, yes. The other question would be if a different object would be used for synchronization that would be a different story.Please correct me if I am missing something here.

I have long been searching for practical example of volatile modifier in Java world, which goes beyond the classic explanation that volatile variables are always read from memory, so if you need that behavior, use volatile. Ok, I got that, but how about some practical use case scenarios? Well, after some research and lots of googling, I found that :

You should use volatile for three reasons :- to avoid thread keep stale values in local cache, that's always the visibility guarantee.- happens-before relationship, which means a volatile write will happens before any further volatile read- to prevent re-ordering of code, which JVM or JIT does for performance reasons

Keep in this in mind, I find following practical scenarios where you can use volatile modifier :1) In double checked locking code ( as given in this article), because the thread which is assigning value to _instance is different than the thread which is getting instance.

2) to make long and double read atomic in Java world. If you don't know, as per Java Memory Model a write to non-volatile double and long variable completes in two steps, where each step writes the 32-bit value. It's possible that one thread can see half value written by another thread. You can prevent this by using volatile keyword.

I don't understand how making the _instance variable volatile, would help. As far as I understand, when a thread leaves a sync block, it will commit all the variables it has changed, to the main memory. Likewise, a thread entering a sync block would always read the values(which it is going to use or change) from the main memory afresh(as it would not know how much time it had been waiting to get into the sync block).

In essence, the thread which enters sync block, immediately after the thread which created the instance left the sync block, will definitely see the _instance as non-null, irrespective of whether _instance was declared as volatile or not.