3

Possible Duplicate:
When exactly do you use the volatile keyword in Java?

When and why volatile modifier is required in java?

I am interested in seeing a real world usage of a volatile modified primitive or object reference.

Community
  • 1
  • 1
Rakesh Goswami
  • 205
  • 1
  • 4
  • 21
  • This is about as specific as asking when `int` is required, or `while` – yshavit May 01 '12 at 04:59
  • http://stackoverflow.com/questions/3488703/when-exactly-do-you-use-the-volatile-keyword-in-java – Francis Upton IV May 01 '12 at 05:00
  • @lukas Agree to disagree, I suppose -- and I'll give a crack at the question. But my point was that `volatile`, like `int`, `while` and lots of other Java constructs, has wide ramifications past just its simple "what does it do." – yshavit May 01 '12 at 05:14
  • 1
    If some of the answers on this page seem a bit... similar to each other... give this URL a click: http://www.java-samples.com/showtutorial.php?tutorialid=331 That page doesn't take into account the improvements to the Java Memory Model made in Java 5, though. – yshavit May 01 '12 at 05:46

4 Answers4

10

volatile modifier will tell the JVM to be cautious of the threads which runs concurrently. Essentially, volatile is used to indicate that a variable's value will be modified by different threads.

Declaring a volatile Java variable means:

  • The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory"

  • Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.

We say "acts as though" in the second point, because to the programmer at least (and probably in most JVM implementations) there is no actual lock object involved.


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 instance variable. For efficiency considerations, each thread can keep its own, private copy of such a shared variable.

The real (or master) copy of the variable is updated at various times, such as when a synchronized method is entered. While this approach works fine, it may be inefficient at times. In some cases, all that really matters is that the master copy of a variable always reflects its current state.

To ensure this, simply specify the variable as volatile, which tells the compiler that it must always use the master copy of a volatile variable (or, at least, always keep any private copies up to date with the master copy, and vice versa). Also, accesses to the master variable must be executed in the precise order in which they are executed on any private copy.

Vineet Menon
  • 728
  • 2
  • 9
  • 25
  • 1
    "Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself." <-- This makes it sound like `myVolatile++` acts as though it's `synchronized (something) { myVolatile++ }`, which isn't so. – yshavit May 01 '12 at 05:03
  • it's just a hint to programmer...no locks are involved... – Vineet Menon May 01 '12 at 05:09
  • so in case of volatile modifier with multi threading no thread local copy of the variable will be maintained ? – Rakesh Goswami May 01 '12 at 05:09
  • there may be a thread local copy of variable... `volatile` keyword is just a hint to jvm to be cautious when syncing the local copies with master copy.... – Vineet Menon May 01 '12 at 05:15
  • @VineetMenon It's a lot more than just a hint -- it sets up a formal relationship between operations that the JVM *must* adhere to, and (in Java 5+) it affects more than just the one volatile field. – yshavit May 01 '12 at 05:17
  • @yshavit: *must*, I didn't knew about.. thx anyway... – Vineet Menon May 01 '12 at 05:19
9

If you are working with the multi-threaded programming, the volatile keyword will be more useful. When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it’s updating the value, it is actually updated in the local cache not in the main variable memory. The other thread which is using the same variable doesn’t know anything about the values changed by the another thread. To avoid this problem, if you declare a variable as volatile, then it will not be stored in the local cache. Whenever thread are updating the values, it is updated to the main memory. So, other threads can access the updated value.

Declaring a variable volatile means

  • There will be no cache maintained means all the changes made in main memory.
  • Access to this variable acts as synchronized block, even though it is in synchronized unit.

Example -

public class Snippet implements Runnable{
volatile int num =0;

public void run(){
    Thread t = Thread.currentThread();
    String name = t.getName();
    if(name.equals("Thread1")){
        num=10;
    }
    else{
        System.out.println("value of num is :"+num);
    }

}
public static void main(String args[]) throws InterruptedException{
    Runnable r = new Snippet();
    Thread t1 = new Thread(r);
    t1.setName("Thread1");
    t1.start();

    Thread.sleep(1000);

    Thread t2 = new Thread(r);
    t2.setName("Thread2");
    t2.start();
}
 }
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
4

(This answer assumes Java 5+ -- before that, volatile had weaker guarantees.)

It's useful when you want to ensure a memory barrier, aka a formal "happens-before" relationship, between a write to a field and a subsequent read to that field by a separate thread. Synchronization can also give you that relationship, as well as other multithreading guarantees, but it's a tad slower and can create synchronization bottlenecks.

One use case is in concurrent collection classes (like ConcurrentHashMap, or LinkedBlockingQueue) where, in conjunction with things like atomic compare-and-set (CAS) operations, you can write correct thread-safe code without having to use synchronized.

yshavit
  • 42,327
  • 7
  • 87
  • 124
  • can you please mention which answer you are talking about – Edge May 01 '12 at 05:45
  • @Edge My answer. It (my answer) is incorrect for Java 1.4 and below, for which there is no happens-before relationship imposed by `volatile`. – yshavit May 01 '12 at 05:47
1

You got good answers for the first question. The second one:

Can any one give me real time scenario of it

IMO, you should never ever you volatile. There are better tools for multithreaded apps. It's a bit bizarre that such a high level language has this keyword. Here is a good read (It's about C#, but Java is similar in this matter).

Lukasz Madon
  • 14,664
  • 14
  • 64
  • 108