SlideShare a Scribd company logo
8/28/2016 How Volatile in Java works? Example of volatile keyword in Java
http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 1/12
Home core java spring hibernate collections multithreading design patterns interview questions coding data structure OOP books About Me
How Volatile in Java works? Example of volatile keyword in Java
How to use Volatile keyword in Java
What is volatile variable in Java and when to use  the volatile variable in Java is a famous
multi‐threading interview question in Java interviews. Though many programmers know
what is a volatile variable but they fail on second part i.e. where to use volatile variable in
Java as it's not common to have a clear understanding and hands‐on on volatile in Java. In
this tutorial, we will address this gap by providing a simple example of the volatile variable
in Java and discussing some when to use the volatile variable in Java. Anyway,  the 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 an int or a boolean variable then  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 from 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.
The Java volatile keyword cannot be used with method or class and it can only be used
with a variable. Java volatile keyword also guarantees visibility and ordering, after Java 5
write to any volatile variable happens before any read into the volatile variable. By the
way use of volatile keyword also prevents compiler or JVM from the reordering of code or
moving away them from synchronization barrier.
The Volatile variable Example in Java
To Understand example of volatile keyword in java let’s go back to Singleton pattern in
Java and see double checked locking in Singleton with Volatile and without the volatile
keyword in java.
/**
 * Java program to demonstrate where to use Volatile keyword in Java.
 * In this example Singleton Instance is declared as volatile variable to ensure
 * every thread see updated value for _instance.
 * 
 * @author Javin Paul
 */
public class Singleton{
private static volatile Singleton _instance; //volatile variable 
public static Singleton getInstance(){
   if(_instance == null){
            synchronized(Singleton.class){
              if(_instance == null)
              _instance = new Singleton();
            }
   }
   return _instance;
}
If you look at the code carefully you will be able to figure out:
1) We are only creating instance one time
Interview Questions
core java interview question (157)
data structure and algorithm (38)
Coding Interview Question (29)
SQL Interview Questions (22)
database interview questions (18)
thread interview questions (18)
servlet interview questions (17)
collections interview questions (15)
spring interview questions (9)
Programming interview question (4)
hibernate interview questions (4)
Recommended Best Practices
3 Method and Constructor overloading best
practices
How string in switch case internally works in Java
7?
Top 10 Programming Best Practices to name
variables and methods
How SSL, HTTPS and Certificates works in Java
Application?
7 tips while dealing with password in Java?
Introduction of How Android works for Java
Programmers
How substring() method works in Java?
Related tutorials
Java debugging tips
Java coding problems
HTML and JavaScript tutorial
Java JEE tutorial
FIX protocol tutorial
Java eclipse tutorial
Java best practices
Java array tutorial
Java troubleshooting guides
Java Tutorials
date and time tutorial (14)
FIX protocol tutorial (16)
java collection tutorial (52)
java IO tutorial (24)
Java JSON tutorial (5)
Java multithreading Tutorials (29)
Java Programming Tutorials (27)
Java xml tutorial (9)
Follow by Email
Followers
Javarevisited
Blog about Java programming language, FIX Protocol, Tibco RV
Search
Email address... Submit
8/28/2016 How Volatile in Java works? Example of volatile keyword in Java
http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 2/12
2) We are creating instance lazily at the time of the first request comes.
If we do not make the _instance variable volatile than the 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.
So in Summary apart from synchronized keyword in Java, volatile keyword is also used to
communicate the content of memory between 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 it's not synchronized in Java already. volatile
keyword in java guarantees that value of the 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.
private boolean bExit;
 while(!bExit) {
    checkUserPosition();
    updateUserPosition();
 }
Followers (3765) Next
Follow
Blog Archive
►  2016 ( 107 )
►  2015 ( 127 )
►  2014 ( 102 )
►  2013 ( 128 )
►  2012 ( 214 )
▼  2011 ( 136 )
►  December ( 27 )
►  November ( 14 )
►  October ( 14 )
►  September ( 20 )
►  August ( 11 )
►  July ( 7 )
▼  June ( 8 )
List of special bash parameter used in Unix or
Li...
3 Exampls to Convert an Array to ArrayList in
Java...
10 example of using Vim or VI editor in UNIX and
L...
3 ways to solve java.lang.NoClassDefFoundError
in ...
How to use Comparator and Comparable in
Java? With...
Top 30 Programming questions asked in Interview
‐ ...
Tibco tutorial : Reliability Parameter Explained
How Volatile in Java works? Example of volatile
ke...
►  May ( 5 )
►  April ( 7 )
►  March ( 3 )
►  February ( 10 )
►  January ( 10 )
►  2010 ( 30 )
Translate this blog
Select Language
Powered by  Translate
Search This Blog
Search
Pages
Privacy Policy
Copyright by Javin Paul 2010‐2016. Powered by
Blogger.
8/28/2016 How Volatile in Java works? Example of volatile keyword in Java
http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 3/12
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.
Also, If you have not read already then I also suggest you read the topic about volatile
variable from Java Concurrency in Practice book by Brian Goetz, one of the must read to
truly understand this complex concept.
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) A volatile variable can be used as an alternative way of achieving synchronization in
Java in some cases, like Visibility. with volatile variable, it's guaranteed that all reader
thread will see updated value of the volatile variable once write operation completed,
without volatile keyword different reader thread may see different values.
3) volatile variable can be used to inform the compiler that a particular field is subject to
be accessed by multiple threads, which will prevent the compiler from doing any
reordering or any kind of optimization which is not desirable in a multi‐threaded
environment. Without volatile variable compiler can re‐order the code, free to cache value
of volatile variable instead of always reading from main memory. like following example
without volatile variable may result in an infinite loop
private boolean isActive = thread;
8/28/2016 How Volatile in Java works? Example of volatile keyword in Java
http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 4/12
private boolean isActive = thread;
public void printMessage(){
  while(isActive){
     System.out.println("Thread is Active");
  }
} 
without the volatile modifier, it's not guaranteed that one Thread sees the updated value
of isActive from other thread. The 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 a 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. The volatile keyword in Java is only application to a variable and using volatile keyword
with class and method is illegal.
2. volatile keyword in Java guarantees that value of the 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 the 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 the use of volatile keyword in Java.
7. An access to a volatile variable in Java never has a 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 mean 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, you don't need to use volatile
keyword with that variable.
8/28/2016 How Volatile in Java works? Example of volatile keyword in Java
http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 5/12
Difference between synchronized and volatile keyword in
Java
What is the difference between volatile and synchronized is another popular core Java
question asked on 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. The volatile keyword in Java is a field modifier while synchronized modifies code blocks
and methods.
2. Synchronized obtains and releases the lock on monitor’s Java volatile keyword doesn't
require that.
3. Threads in Java can be blocked for waiting for any monitor in case of synchronized, that
is not the case with the volatile keyword in Java.
4. Synchronized method affects performance more than a volatile keyword in Java.
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 the 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 short, 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
going thorough FAQ on Java Memory Model here which explains happens‐before operations
quite well.
Further Reading
The Java concurrency in Practice by Brian Goetz (see here)
Java Threads By Scott Oaks and Henry Wong (see here)
Other Java concurrency tutorials from Javarevisited you may like
1. Difference between Runnable and Thread in Java
2. How to use CyclicBarrier in Java with Example
3. What is ConcurrentHashMap in Java
4. How to use CountDownLatch in Java with Example
5. How to solve producer consumer problem with BlockingQueue in Java
6. What is thread‐safe class, How to write
Posted by Javin Paul
Labels: core java , core java interview question , java 5 tutorial , Java multithreading Tutorials , thread
interview questions
Location: United States
45 comments :
Anand said...
+213   Recommend this on Google
8/28/2016 How Volatile in Java works? Example of volatile keyword in Java
http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 6/12
This one is a Gem Javin!!!
Keep up the good work.
Anand.
June 29, 2011 at 6:21 AM
Anonymous said...
hi, what is difference between volatile and synchronized keyword in java ? Can we use volatile in place of
synchronized ? what will happen if we don't make variable volatile in Java ?
August 11, 2011 at 11:10 PM
Javin @ String vs StringBuffer said...
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
August 13, 2011 at 6:24 PM
Barchist said...
Why not we can use volatile keyword with method ? why only variable needs to be volatile ? yes it may look some
insane questions but I just want to know basics of volatile keyword ?
October 7, 2011 at 3:29 AM
Anonymous said...
Volatile in Java is more of a documentation keyword, I never seen much usage of volatile keyword in most of
project, what I have seen is synchronized and synchronized.
December 1, 2011 at 2:48 AM
Aban said...
Hi,
For understanding and testing purpose I write a small pice of code as following:
VolatileTest.java
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
public class VolatileTest extends Thread {
private volatile int testValue;
private volatile boolean ready;
public VolatileTest(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 3; i++) {
try {
if (getName().equals("T1")) {
ready = true;
testValue = i;
System.out.println(getName() + " :: " + ready + " :: " + testValue);
}
if (getName().equals("T2")) {
System.out.println(getName() + " :: " + ready + " :: " + testValue);
}
Thread.sleep(1000);
} catch (InterruptedException exception) {
exception.printStackTrace();
}
}
}
}
TestVol .java
‐‐‐‐‐‐‐‐‐‐‐‐‐‐
public class TestVol {
public static void main(String[] args) {
new VolatileTest("T1").start();
new VolatileTest("T2").start();
}
}
8/28/2016 How Volatile in Java works? Example of volatile keyword in Java
http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 7/12
I am getting following output:
T1 :: true :: 0
T2 :: false :: 0
T1 :: true :: 1
T2 :: false :: 0
T1 :: true :: 2
T2 :: false :: 0
Can you please help me to understand, why this result is comming. As per my understanding, I should get "T2 ::
true :: 0" (second line).
Regards,
Aban
December 6, 2011 at 2:13 AM
Javin @ spring interview questions answers said...
Hi Aban, line 2 is correct since you are using two separate object of VolatileTest default value for boolean ready
is false which is displaying. try using one object and share it between two threads.
December 6, 2011 at 5:23 AM
Issamu said...
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.
December 8, 2011 at 3:32 PM
Chris said...
you double‐check‐lock in the singleton, but it states on the java sun documentation (which you've linked to) that
this doesnt work...
http://java.sun.com/developer/technicalArticles/Programming/singletons/
http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
love the blog though
December 28, 2011 at 5:47 AM
Javin @ spring interview questions answers said...
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"
December 28, 2011 at 5:57 AM
Peter Lawrey said...
This covers the issues well.
I would comment that the simplest singleton pattern is
enum Singleton { INSTANCE; }
its thread safe and lazy loading.
January 23, 2012 at 5:21 AM
Javin @ race condition in java said...
@Unknown,Thanks for comment. Glad to know that you like this Java volatile example and tutorial. you may like
my other post on threading as well e.g. Why wait and notify are defined in Object class
March 24, 2012 at 8:21 PM
Anonymous said...
I read your blog often, however, I think you made a mistake in the following line
"....all other thread will not be able to see value of _instance as not null and they will believe its still null."
It should be more like " all other threads will see the partially constructed value of _instance and return the
value thinking it is not null."
This is according to wikipedia..http://en.wikipedia.org/wiki/Double‐checked_locking
June 10, 2012 at 5:39 PM
8/28/2016 How Volatile in Java works? Example of volatile keyword in Java
http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 8/12
Anonymous said...
Can a volatile variable in Java be static ? If not why ?
What difference it make to mark a volatile variable final ?
August 21, 2012 at 7:25 PM
Anonymous said...
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/
It also explains why you probably shouldn't bother with double checked locking, something missing here.
September 27, 2012 at 2:57 AM
Existentior said...
This is very good stuff. You are a good programmer, Javin. There are not many like you out there. My sincere
thanks to you for this article. It helps many people understand the details.
October 5, 2012 at 10:47 AM
Chatar said...
This is not true Jatin ‐>
3. In Java reads and writes are atomic for all variables declared using Java volatile keyword (including long and
double variables).
To make read/ write automatic you need to you CAS operation which are implemented using Atomic*** in Java 1.5
concurrent package or last choice is explicit synchronization.
November 4, 2012 at 5:49 AM
tang07059 said...
Do you know the difference between Hashtable (synchronized) and Volatile HashSet (seems also synchronized)?
November 27, 2012 at 12:12 PM
Anonymous said...
Thank you for your post!
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?
February 18, 2013 at 5:01 PM
Steve said...
@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.
March 4, 2013 at 1:10 AM
Anonymous said...
what do you mean by after creation lost the CPU
March 22, 2013 at 3:15 PM
Anonymous said...
8/28/2016 How Volatile in Java works? Example of volatile keyword in Java
http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 9/12
Amazing explanation! Thanks for that.
In the differences section point 5, you say that ‐
"synchronized synchronizes the value of all variable between thread memory and "main" memory"
Isn't this incorrect ? If it was true, then there would be no need for Volatile keyword. (Since volatile is always
used in conjunction with synchronized)
May 24, 2013 at 12:20 AM
Javin @ abstract class interface interview questions said...
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.
May 24, 2013 at 4:02 AM
Anonymous said...
Thanks Javin.
‐ 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
May 24, 2013 at 12:33 PM
Javin @ Java Classloder Working said...
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.
May 24, 2013 at 8:48 PM
Anonymous said...
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.
September 26, 2013 at 3:28 AM
palak pal said...
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
http://www.youtube.com/watch?v=y8_jrkHEZpg&list=PLrUFyg1unBb9bhxd9ck0LEL89UB_G6‐ZJ&index=5
October 28, 2013 at 12:46 PM
John said...
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.
December 5, 2013 at 1:19 PM
Arfeen Khan said...
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.
8/28/2016 How Volatile in Java works? Example of volatile keyword in Java
http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 10/12
Thank you.
March 30, 2014 at 10:46 PM
RuGu said...
Hi Javin
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.
May 7, 2014 at 11:49 PM
Jakub Stransky said...
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.
May 30, 2014 at 12:20 AM
Ajay Kumar said...
Hi,
I guess above example will work fine without volatile keyword also, because changes made in a synchronized
block are also visible to other threads, please correct me If I am wrong.
May 30, 2014 at 12:46 PM
Anonymous said...
What does volatile do? section in this post also explains it well
https://www.cs.umd.edu/users/pugh/java/memoryModel/jsr‐133‐faq.html#volatile
June 22, 2014 at 9:07 AM
Anonymous said...
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.
3) word tearing
August 26, 2014 at 3:24 AM
renjith alexander said...
Regarding the usage of volatile in double checked locking:
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).
8/28/2016 How Volatile in Java works? Example of volatile keyword in Java
http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 11/12
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.
January 28, 2015 at 2:59 AM
Bhupender Giri said...
Hi,
Thanks for your post but point no. 3 & 6 are contradictory under "Important points on Volatile keyword in Java"
section.
In my opinion, Volatile only guarantees "Visibility" but not atomicity. Since long/double variable does not support
atomicity so possible solution for them would be using Atomic* apis.
August 4, 2015 at 6:23 PM
Anonymous said...
Accoring to servlet specification, container makes one instance. and specification says that "do not mark service()
method as a syncronized, because at that time the servlet container cannot use the instance pool approach. One
instance and pooling, it's confused. When I see your first example, for singleton, I really know how to make
pooling for singleton objects. Volatile keyword supply this functionality for multi processor computers behind the
scenes. Thank you.
December 16, 2015 at 1:53 AM
Pk Hafeez said...
Nice post !! What i learnt from this post in short ‐‐‐‐> if two threads are both reading and writing to a shared
variable, then using the volatile keyword for that is not enough. You need to use a synchronized in that case to
guarantee that the reading and writing of the variable is atomic. Reading or writing a volatile variable does not
block threads reading or writing. For this to happen you must use the synchronized keyword around critical
sections. Instead use Atomic classes from concurrent package for primitive wrappers.
December 31, 2015 at 4:19 AM
Lakshmi Ganesh Muthuluru said...
If the threads have the working memory, does that not mean they are having their own memory to some extent?
can someone please explain this?
January 4, 2016 at 10:56 PM
Javin Paul said...
@Lakshmi, that true. Thread has their own memory and that's called Stack memory. Every thread has Stack
memory which you can configure using ‐Xss parameter.
January 5, 2016 at 4:13 AM
Shimpu Borthakur said...
I have one queston in mind. Suppose I make a variable volatile and that variable is being used by two threads
separately in a method which doing some calculation and return the new value of the variable.
Now how this thing is atomic as the second thread is reading the variable before it gets changed from the first
thread. It didn't got the updated value of the variable from the first thread.
Please help me understand this.
February 10, 2016 at 1:51 AM
Anonymous said...
Can we use volatile modifier with interface variables ?
March 26, 2016 at 12:48 PM
Anonymous said...
Hi all,
Why did the author use synchronized block rather than synchronized method?
I mean, was there any clear advantage for that?
Thanks
March 27, 2016 at 2:50 PM
Javin Paul said...
@It reduces the scope of locking i.e lock will be held for code which really needs locking and for less time. This
will result in better performance.
March 28, 2016 at 3:43 AM
Tao Shibo said...
8/28/2016 How Volatile in Java works? Example of volatile keyword in Java
http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 12/12
Newer Post Older Post
I think the reason why _instance in Singleton class must be volatile you described here is incorrect.
The real reason is other thread might read partial initialized instance, which might cause error.
see https://en.wikipedia.org/wiki/Double‐checked_locking#Usage_in_Java
July 19, 2016 at 2:14 AM
Post a Comment
Sign out
  Notify me
Enter your comment...
Comment as:  PRADEEP KUMAR (Google)
Publish
  Preview
Home
Subscribe to: Post Comments ( Atom )
References
MSDN Tech Network
Tutorialspoint
Official JQuery website
Eclipse IDE Download
Hibernate framework
Spring Framework
Oracle Java Tech Network
Download JDK
Java 8 API Reference

More Related Content

PDF
Java Concurrency Starter Kit
PDF
Advanced java interview questions
PDF
Java/J2EE interview Qestions
PDF
Java object oriented programming - OOPS
PDF
Class notes(week 9) on multithreading
PDF
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
PDF
Java interview question
DOCX
Design pattern application
Java Concurrency Starter Kit
Advanced java interview questions
Java/J2EE interview Qestions
Java object oriented programming - OOPS
Class notes(week 9) on multithreading
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Java interview question
Design pattern application

What's hot (20)

PDF
Concurrency on the JVM
PDF
Java design pattern tutorial
PDF
Top 10 Java Interview Questions and Answers 2014
PDF
What are the different java interview questions you need to know?
PDF
Java Interview Questions by NageswaraRao
DOCX
What are the different java interview questions you need to know?
PDF
20 most important java programming interview questions
PDF
37 Java Interview Questions
DOCX
Basic java important interview questions and answers to secure a job
DOCX
Java interview questions and answers for cognizant By Data Council Pune
PDF
Java interview questions and answers
PPTX
OCA Java SE 8 Exam Chapter 5 Class Design
DOCX
Java questions for viva
PPT
8 most expected java interview questions
PPTX
Effective Java - Chapter 2: Creating and Destroying Objects
PDF
Core Java Tutorial
PPS
Dacj 1-3 a
PPTX
Introduction to Java programming - Java tutorial for beginners to teach Java ...
PPTX
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
PPTX
Type Annotations in Java 8
Concurrency on the JVM
Java design pattern tutorial
Top 10 Java Interview Questions and Answers 2014
What are the different java interview questions you need to know?
Java Interview Questions by NageswaraRao
What are the different java interview questions you need to know?
20 most important java programming interview questions
37 Java Interview Questions
Basic java important interview questions and answers to secure a job
Java interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers
OCA Java SE 8 Exam Chapter 5 Class Design
Java questions for viva
8 most expected java interview questions
Effective Java - Chapter 2: Creating and Destroying Objects
Core Java Tutorial
Dacj 1-3 a
Introduction to Java programming - Java tutorial for beginners to teach Java ...
OCA Java SE 8 Exam Chapter 4 Methods Encapsulation
Type Annotations in Java 8
Ad

Similar to Volatile keyword (20)

PPTX
Object-Oriented Programming with Java UNIT 1
PPTX
Interview-QA.pptx
PDF
Java Simplified: Understanding Programming Basics
PDF
Bt0074 oops with java2
PDF
java notes.pdf
PPTX
Java_Roadmap.pptx
PDF
Java 10 - Key Note
PPT
Java interview-questions-and-answers
PDF
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
PDF
Java Faqs useful for freshers and experienced
PPTX
Unit No 4 Exception Handling and Multithreading.pptx
DOC
Java questions and answers jan bask.net
PDF
Java data types, variables and jvm
PDF
Top 371 java fa qs useful for freshers and experienced
DOCX
PDF
Java Basics Presentation
PPTX
Core java
PPT
Java for Mainframers
PDF
Java basic concept
DOCX
Java 3 rd sem. 2012 aug.ASSIGNMENT
Object-Oriented Programming with Java UNIT 1
Interview-QA.pptx
Java Simplified: Understanding Programming Basics
Bt0074 oops with java2
java notes.pdf
Java_Roadmap.pptx
Java 10 - Key Note
Java interview-questions-and-answers
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
Java Faqs useful for freshers and experienced
Unit No 4 Exception Handling and Multithreading.pptx
Java questions and answers jan bask.net
Java data types, variables and jvm
Top 371 java fa qs useful for freshers and experienced
Java Basics Presentation
Core java
Java for Mainframers
Java basic concept
Java 3 rd sem. 2012 aug.ASSIGNMENT
Ad

More from charan kumar (11)

PDF
Tree map (java platform se 8 )
PDF
The set interface (the java™ tutorials collections interfaces)
PDF
The map interface (the java™ tutorials collections interfaces)
PDF
The list interface (the java™ tutorials collections interfaces)
PDF
Linked list (java platform se 8 )
PDF
Linked hashmap (java platform se 8 )
PDF
Hash set (java platform se 8 )
PDF
Hash map (java platform se 8 )
PDF
Collectn framework
PDF
Collectn framework copy
PDF
Array list (java platform se 8 )
Tree map (java platform se 8 )
The set interface (the java™ tutorials collections interfaces)
The map interface (the java™ tutorials collections interfaces)
The list interface (the java™ tutorials collections interfaces)
Linked list (java platform se 8 )
Linked hashmap (java platform se 8 )
Hash set (java platform se 8 )
Hash map (java platform se 8 )
Collectn framework
Collectn framework copy
Array list (java platform se 8 )

Recently uploaded (20)

PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
master seminar digital applications in india
PPTX
Lesson notes of climatology university.
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
RMMM.pdf make it easy to upload and study
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Basic Mud Logging Guide for educational purpose
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Pharma ospi slides which help in ospi learning
PPTX
PPH.pptx obstetrics and gynecology in nursing
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Microbial disease of the cardiovascular and lymphatic systems
master seminar digital applications in india
Lesson notes of climatology university.
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Cell Structure & Organelles in detailed.
Insiders guide to clinical Medicine.pdf
Microbial diseases, their pathogenesis and prophylaxis
RMMM.pdf make it easy to upload and study
GDM (1) (1).pptx small presentation for students
human mycosis Human fungal infections are called human mycosis..pptx
102 student loan defaulters named and shamed – Is someone you know on the list?
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Basic Mud Logging Guide for educational purpose
TR - Agricultural Crops Production NC III.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Renaissance Architecture: A Journey from Faith to Humanism
Pharma ospi slides which help in ospi learning
PPH.pptx obstetrics and gynecology in nursing

Volatile keyword

  • 1. 8/28/2016 How Volatile in Java works? Example of volatile keyword in Java http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 1/12 Home core java spring hibernate collections multithreading design patterns interview questions coding data structure OOP books About Me How Volatile in Java works? Example of volatile keyword in Java How to use Volatile keyword in Java What is volatile variable in Java and when to use  the volatile variable in Java is a famous multi‐threading interview question in Java interviews. Though many programmers know what is a volatile variable but they fail on second part i.e. where to use volatile variable in Java as it's not common to have a clear understanding and hands‐on on volatile in Java. In this tutorial, we will address this gap by providing a simple example of the volatile variable in Java and discussing some when to use the volatile variable in Java. Anyway,  the 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 an int or a boolean variable then  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 from 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. The Java volatile keyword cannot be used with method or class and it can only be used with a variable. Java volatile keyword also guarantees visibility and ordering, after Java 5 write to any volatile variable happens before any read into the volatile variable. By the way use of volatile keyword also prevents compiler or JVM from the reordering of code or moving away them from synchronization barrier. The Volatile variable Example in Java To Understand example of volatile keyword in java let’s go back to Singleton pattern in Java and see double checked locking in Singleton with Volatile and without the volatile keyword in java. /**  * Java program to demonstrate where to use Volatile keyword in Java.  * In this example Singleton Instance is declared as volatile variable to ensure  * every thread see updated value for _instance.  *   * @author Javin Paul  */ public class Singleton{ private static volatile Singleton _instance; //volatile variable  public static Singleton getInstance(){    if(_instance == null){             synchronized(Singleton.class){               if(_instance == null)               _instance = new Singleton();             }    }    return _instance; } If you look at the code carefully you will be able to figure out: 1) We are only creating instance one time Interview Questions core java interview question (157) data structure and algorithm (38) Coding Interview Question (29) SQL Interview Questions (22) database interview questions (18) thread interview questions (18) servlet interview questions (17) collections interview questions (15) spring interview questions (9) Programming interview question (4) hibernate interview questions (4) Recommended Best Practices 3 Method and Constructor overloading best practices How string in switch case internally works in Java 7? Top 10 Programming Best Practices to name variables and methods How SSL, HTTPS and Certificates works in Java Application? 7 tips while dealing with password in Java? Introduction of How Android works for Java Programmers How substring() method works in Java? Related tutorials Java debugging tips Java coding problems HTML and JavaScript tutorial Java JEE tutorial FIX protocol tutorial Java eclipse tutorial Java best practices Java array tutorial Java troubleshooting guides Java Tutorials date and time tutorial (14) FIX protocol tutorial (16) java collection tutorial (52) java IO tutorial (24) Java JSON tutorial (5) Java multithreading Tutorials (29) Java Programming Tutorials (27) Java xml tutorial (9) Follow by Email Followers Javarevisited Blog about Java programming language, FIX Protocol, Tibco RV Search Email address... Submit
  • 2. 8/28/2016 How Volatile in Java works? Example of volatile keyword in Java http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 2/12 2) We are creating instance lazily at the time of the first request comes. If we do not make the _instance variable volatile than the 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. So in Summary apart from synchronized keyword in Java, volatile keyword is also used to communicate the content of memory between 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 it's not synchronized in Java already. volatile keyword in java guarantees that value of the 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. private boolean bExit;  while(!bExit) {     checkUserPosition();     updateUserPosition();  } Followers (3765) Next Follow Blog Archive ►  2016 ( 107 ) ►  2015 ( 127 ) ►  2014 ( 102 ) ►  2013 ( 128 ) ►  2012 ( 214 ) ▼  2011 ( 136 ) ►  December ( 27 ) ►  November ( 14 ) ►  October ( 14 ) ►  September ( 20 ) ►  August ( 11 ) ►  July ( 7 ) ▼  June ( 8 ) List of special bash parameter used in Unix or Li... 3 Exampls to Convert an Array to ArrayList in Java... 10 example of using Vim or VI editor in UNIX and L... 3 ways to solve java.lang.NoClassDefFoundError in ... How to use Comparator and Comparable in Java? With... Top 30 Programming questions asked in Interview ‐ ... Tibco tutorial : Reliability Parameter Explained How Volatile in Java works? Example of volatile ke... ►  May ( 5 ) ►  April ( 7 ) ►  March ( 3 ) ►  February ( 10 ) ►  January ( 10 ) ►  2010 ( 30 ) Translate this blog Select Language Powered by  Translate Search This Blog Search Pages Privacy Policy Copyright by Javin Paul 2010‐2016. Powered by Blogger.
  • 3. 8/28/2016 How Volatile in Java works? Example of volatile keyword in Java http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 3/12 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. Also, If you have not read already then I also suggest you read the topic about volatile variable from Java Concurrency in Practice book by Brian Goetz, one of the must read to truly understand this complex concept. 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) A volatile variable can be used as an alternative way of achieving synchronization in Java in some cases, like Visibility. with volatile variable, it's guaranteed that all reader thread will see updated value of the volatile variable once write operation completed, without volatile keyword different reader thread may see different values. 3) volatile variable can be used to inform the compiler that a particular field is subject to be accessed by multiple threads, which will prevent the compiler from doing any reordering or any kind of optimization which is not desirable in a multi‐threaded environment. Without volatile variable compiler can re‐order the code, free to cache value of volatile variable instead of always reading from main memory. like following example without volatile variable may result in an infinite loop private boolean isActive = thread;
  • 4. 8/28/2016 How Volatile in Java works? Example of volatile keyword in Java http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 4/12 private boolean isActive = thread; public void printMessage(){   while(isActive){      System.out.println("Thread is Active");   } }  without the volatile modifier, it's not guaranteed that one Thread sees the updated value of isActive from other thread. The 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 a 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. The volatile keyword in Java is only application to a variable and using volatile keyword with class and method is illegal. 2. volatile keyword in Java guarantees that value of the 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 the 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 the use of volatile keyword in Java. 7. An access to a volatile variable in Java never has a 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 mean 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, you don't need to use volatile keyword with that variable.
  • 5. 8/28/2016 How Volatile in Java works? Example of volatile keyword in Java http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 5/12 Difference between synchronized and volatile keyword in Java What is the difference between volatile and synchronized is another popular core Java question asked on 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. The volatile keyword in Java is a field modifier while synchronized modifies code blocks and methods. 2. Synchronized obtains and releases the lock on monitor’s Java volatile keyword doesn't require that. 3. Threads in Java can be blocked for waiting for any monitor in case of synchronized, that is not the case with the volatile keyword in Java. 4. Synchronized method affects performance more than a volatile keyword in Java. 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 the 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 short, 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 going thorough FAQ on Java Memory Model here which explains happens‐before operations quite well. Further Reading The Java concurrency in Practice by Brian Goetz (see here) Java Threads By Scott Oaks and Henry Wong (see here) Other Java concurrency tutorials from Javarevisited you may like 1. Difference between Runnable and Thread in Java 2. How to use CyclicBarrier in Java with Example 3. What is ConcurrentHashMap in Java 4. How to use CountDownLatch in Java with Example 5. How to solve producer consumer problem with BlockingQueue in Java 6. What is thread‐safe class, How to write Posted by Javin Paul Labels: core java , core java interview question , java 5 tutorial , Java multithreading Tutorials , thread interview questions Location: United States 45 comments : Anand said... +213   Recommend this on Google
  • 6. 8/28/2016 How Volatile in Java works? Example of volatile keyword in Java http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 6/12 This one is a Gem Javin!!! Keep up the good work. Anand. June 29, 2011 at 6:21 AM Anonymous said... hi, what is difference between volatile and synchronized keyword in java ? Can we use volatile in place of synchronized ? what will happen if we don't make variable volatile in Java ? August 11, 2011 at 11:10 PM Javin @ String vs StringBuffer said... 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 August 13, 2011 at 6:24 PM Barchist said... Why not we can use volatile keyword with method ? why only variable needs to be volatile ? yes it may look some insane questions but I just want to know basics of volatile keyword ? October 7, 2011 at 3:29 AM Anonymous said... Volatile in Java is more of a documentation keyword, I never seen much usage of volatile keyword in most of project, what I have seen is synchronized and synchronized. December 1, 2011 at 2:48 AM Aban said... Hi, For understanding and testing purpose I write a small pice of code as following: VolatileTest.java ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ public class VolatileTest extends Thread { private volatile int testValue; private volatile boolean ready; public VolatileTest(String str) { super(str); } public void run() { for (int i = 0; i < 3; i++) { try { if (getName().equals("T1")) { ready = true; testValue = i; System.out.println(getName() + " :: " + ready + " :: " + testValue); } if (getName().equals("T2")) { System.out.println(getName() + " :: " + ready + " :: " + testValue); } Thread.sleep(1000); } catch (InterruptedException exception) { exception.printStackTrace(); } } } } TestVol .java ‐‐‐‐‐‐‐‐‐‐‐‐‐‐ public class TestVol { public static void main(String[] args) { new VolatileTest("T1").start(); new VolatileTest("T2").start(); } }
  • 7. 8/28/2016 How Volatile in Java works? Example of volatile keyword in Java http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 7/12 I am getting following output: T1 :: true :: 0 T2 :: false :: 0 T1 :: true :: 1 T2 :: false :: 0 T1 :: true :: 2 T2 :: false :: 0 Can you please help me to understand, why this result is comming. As per my understanding, I should get "T2 :: true :: 0" (second line). Regards, Aban December 6, 2011 at 2:13 AM Javin @ spring interview questions answers said... Hi Aban, line 2 is correct since you are using two separate object of VolatileTest default value for boolean ready is false which is displaying. try using one object and share it between two threads. December 6, 2011 at 5:23 AM Issamu said... 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. December 8, 2011 at 3:32 PM Chris said... you double‐check‐lock in the singleton, but it states on the java sun documentation (which you've linked to) that this doesnt work... http://java.sun.com/developer/technicalArticles/Programming/singletons/ http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html love the blog though December 28, 2011 at 5:47 AM Javin @ spring interview questions answers said... 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" December 28, 2011 at 5:57 AM Peter Lawrey said... This covers the issues well. I would comment that the simplest singleton pattern is enum Singleton { INSTANCE; } its thread safe and lazy loading. January 23, 2012 at 5:21 AM Javin @ race condition in java said... @Unknown,Thanks for comment. Glad to know that you like this Java volatile example and tutorial. you may like my other post on threading as well e.g. Why wait and notify are defined in Object class March 24, 2012 at 8:21 PM Anonymous said... I read your blog often, however, I think you made a mistake in the following line "....all other thread will not be able to see value of _instance as not null and they will believe its still null." It should be more like " all other threads will see the partially constructed value of _instance and return the value thinking it is not null." This is according to wikipedia..http://en.wikipedia.org/wiki/Double‐checked_locking June 10, 2012 at 5:39 PM
  • 8. 8/28/2016 How Volatile in Java works? Example of volatile keyword in Java http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 8/12 Anonymous said... Can a volatile variable in Java be static ? If not why ? What difference it make to mark a volatile variable final ? August 21, 2012 at 7:25 PM Anonymous said... 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/ It also explains why you probably shouldn't bother with double checked locking, something missing here. September 27, 2012 at 2:57 AM Existentior said... This is very good stuff. You are a good programmer, Javin. There are not many like you out there. My sincere thanks to you for this article. It helps many people understand the details. October 5, 2012 at 10:47 AM Chatar said... This is not true Jatin ‐> 3. In Java reads and writes are atomic for all variables declared using Java volatile keyword (including long and double variables). To make read/ write automatic you need to you CAS operation which are implemented using Atomic*** in Java 1.5 concurrent package or last choice is explicit synchronization. November 4, 2012 at 5:49 AM tang07059 said... Do you know the difference between Hashtable (synchronized) and Volatile HashSet (seems also synchronized)? November 27, 2012 at 12:12 PM Anonymous said... Thank you for your post! 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? February 18, 2013 at 5:01 PM Steve said... @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. March 4, 2013 at 1:10 AM Anonymous said... what do you mean by after creation lost the CPU March 22, 2013 at 3:15 PM Anonymous said...
  • 9. 8/28/2016 How Volatile in Java works? Example of volatile keyword in Java http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 9/12 Amazing explanation! Thanks for that. In the differences section point 5, you say that ‐ "synchronized synchronizes the value of all variable between thread memory and "main" memory" Isn't this incorrect ? If it was true, then there would be no need for Volatile keyword. (Since volatile is always used in conjunction with synchronized) May 24, 2013 at 12:20 AM Javin @ abstract class interface interview questions said... 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. May 24, 2013 at 4:02 AM Anonymous said... Thanks Javin. ‐ 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 May 24, 2013 at 12:33 PM Javin @ Java Classloder Working said... 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. May 24, 2013 at 8:48 PM Anonymous said... 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. September 26, 2013 at 3:28 AM palak pal said... 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 http://www.youtube.com/watch?v=y8_jrkHEZpg&list=PLrUFyg1unBb9bhxd9ck0LEL89UB_G6‐ZJ&index=5 October 28, 2013 at 12:46 PM John said... 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. December 5, 2013 at 1:19 PM Arfeen Khan said... 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.
  • 10. 8/28/2016 How Volatile in Java works? Example of volatile keyword in Java http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 10/12 Thank you. March 30, 2014 at 10:46 PM RuGu said... Hi Javin 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. May 7, 2014 at 11:49 PM Jakub Stransky said... 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. May 30, 2014 at 12:20 AM Ajay Kumar said... Hi, I guess above example will work fine without volatile keyword also, because changes made in a synchronized block are also visible to other threads, please correct me If I am wrong. May 30, 2014 at 12:46 PM Anonymous said... What does volatile do? section in this post also explains it well https://www.cs.umd.edu/users/pugh/java/memoryModel/jsr‐133‐faq.html#volatile June 22, 2014 at 9:07 AM Anonymous said... 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. 3) word tearing August 26, 2014 at 3:24 AM renjith alexander said... Regarding the usage of volatile in double checked locking: 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).
  • 11. 8/28/2016 How Volatile in Java works? Example of volatile keyword in Java http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 11/12 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. January 28, 2015 at 2:59 AM Bhupender Giri said... Hi, Thanks for your post but point no. 3 & 6 are contradictory under "Important points on Volatile keyword in Java" section. In my opinion, Volatile only guarantees "Visibility" but not atomicity. Since long/double variable does not support atomicity so possible solution for them would be using Atomic* apis. August 4, 2015 at 6:23 PM Anonymous said... Accoring to servlet specification, container makes one instance. and specification says that "do not mark service() method as a syncronized, because at that time the servlet container cannot use the instance pool approach. One instance and pooling, it's confused. When I see your first example, for singleton, I really know how to make pooling for singleton objects. Volatile keyword supply this functionality for multi processor computers behind the scenes. Thank you. December 16, 2015 at 1:53 AM Pk Hafeez said... Nice post !! What i learnt from this post in short ‐‐‐‐> if two threads are both reading and writing to a shared variable, then using the volatile keyword for that is not enough. You need to use a synchronized in that case to guarantee that the reading and writing of the variable is atomic. Reading or writing a volatile variable does not block threads reading or writing. For this to happen you must use the synchronized keyword around critical sections. Instead use Atomic classes from concurrent package for primitive wrappers. December 31, 2015 at 4:19 AM Lakshmi Ganesh Muthuluru said... If the threads have the working memory, does that not mean they are having their own memory to some extent? can someone please explain this? January 4, 2016 at 10:56 PM Javin Paul said... @Lakshmi, that true. Thread has their own memory and that's called Stack memory. Every thread has Stack memory which you can configure using ‐Xss parameter. January 5, 2016 at 4:13 AM Shimpu Borthakur said... I have one queston in mind. Suppose I make a variable volatile and that variable is being used by two threads separately in a method which doing some calculation and return the new value of the variable. Now how this thing is atomic as the second thread is reading the variable before it gets changed from the first thread. It didn't got the updated value of the variable from the first thread. Please help me understand this. February 10, 2016 at 1:51 AM Anonymous said... Can we use volatile modifier with interface variables ? March 26, 2016 at 12:48 PM Anonymous said... Hi all, Why did the author use synchronized block rather than synchronized method? I mean, was there any clear advantage for that? Thanks March 27, 2016 at 2:50 PM Javin Paul said... @It reduces the scope of locking i.e lock will be held for code which really needs locking and for less time. This will result in better performance. March 28, 2016 at 3:43 AM Tao Shibo said...
  • 12. 8/28/2016 How Volatile in Java works? Example of volatile keyword in Java http://javarevisited.blogspot.com/2011/06/volatile­keyword­java­example­tutorial.html 12/12 Newer Post Older Post I think the reason why _instance in Singleton class must be volatile you described here is incorrect. The real reason is other thread might read partial initialized instance, which might cause error. see https://en.wikipedia.org/wiki/Double‐checked_locking#Usage_in_Java July 19, 2016 at 2:14 AM Post a Comment Sign out   Notify me Enter your comment... Comment as:  PRADEEP KUMAR (Google) Publish   Preview Home Subscribe to: Post Comments ( Atom ) References MSDN Tech Network Tutorialspoint Official JQuery website Eclipse IDE Download Hibernate framework Spring Framework Oracle Java Tech Network Download JDK Java 8 API Reference