The code example which can prove "volatile" declare should be used
Asked Answered
A

6

16

Currently I can't understand when we should use volatile to declare variable.

I have do some study and searched some materials about it for a long time and know that when a field is declared volatile, the compiler and runtime are put on notice that this variable is shared and that operations on it should not be reordered with other memory operations.

However, I still can't understand in what scenario we should use it. I mean can someone provide any example code which can prove that using "volatile" brings benefit or solve problems compare to without using it?

Accompanist answered 28/4, 2011 at 9:56 Comment(3)
volatile (and many other concurrency-related aspects) are very hard to demonstrate, because if you use them wrongly, then they may still appear to work correctly and not show a problem until a very specific condition occurs and leads to a problem.Argot
I have tried this myself and produced a test which passes values between threaded using a non-voltile field one billion times successfully, however fails relatively quickly when the same box is loaded. Even timing the performance impact of volatile is very difficult are it depends on lots of factors.Labroid
Have a look at this post: stackoverflow.com/questions/7855700/…Underclothes
S
21

Here is an example of why volatile is necessary. If you remove the keyword volatile, thread 1 may never terminate. (When I tested on Java 1.6 Hotspot on Linux, this was indeed the case - your results may vary as the JVM is not obliged to do any caching of variables not marked volatile.)

public class ThreadTest {
  volatile boolean running = true;

  public void test() {
    new Thread(new Runnable() {
      public void run() {
        int counter = 0;
        while (running) {
          counter++;
        }
        System.out.println("Thread 1 finished. Counted up to " + counter);
      }
    }).start();
    new Thread(new Runnable() {
      public void run() {
        // Sleep for a bit so that thread 1 has a chance to start
        try {
          Thread.sleep(100);
        } catch (InterruptedException ignored) { 
         // catch block
        }
        System.out.println("Thread 2 finishing");
        running = false;
      }
    }).start();
  }

  public static void main(String[] args) {
    new ThreadTest().test();
  }
}
Sapphism answered 28/4, 2011 at 10:12 Comment(8)
Sorry, I tried to remove "volatile" keyword and run the program for many times, but every time thread 1 can be terminated. I think for the code you provided even without "volatile" thread 1 can always be terminated every time.Accompanist
@Eric: it gives the effect I describe on two different machines running Java 6 JVMs. I guess I should have phrased it differently. It is only guaranteed to terminate if the volatile keyword is present. If it's not present, the JVM is free to cache the value of running, so thread 1 need not terminate. However, it isn't forced to cache the value.Sapphism
Keeping "volatile" present will terminate thread 1 as soon as 'running' is set false in thread 2. But if remove "volatile", thread 1 may won't terminate even after 'running' is set false in thread2, when thread will terminate depends on when JVM update "running" value in thread 1. Do you mean that??? But if "running" has been set 'false' in thread 2, why thread1 can't get the right value??? If so I think JVM behave wrong.Accompanist
The JVM is not behaving wrongly. Without volatile (or synchronization, or something else which forces a 'happens-before' relationship), thread 1 need not see the change made by thread 2.Sapphism
@Eric: that's exactly the problem: "correct behaviour" is not equivalent to "intuitive behaviour". JVMs are free to cache values (for example in the register of a CPU) if it is read repeatedly and need not read it from main memory each time. Specifying that a variable is volatile disables this caching!Argot
@Simon Nickerson: thanks for your help. How about this example: class TestThread extends Thread { private boolean running = true; public void run() { while(running) { //do something } } public void setStop() { running = false; } } The method 'setStop' will be invoked in another thread which wants to stop 'TestThread'. So here I didn't mark running as volatile so there is a chance that TestThread won't stop immediately (even maybe never stops) after setStop() is invoked in another thread, right? Here the safe way is that I need to mark running as volatile, right?Accompanist
Thanks Simon! You helped me a lot.Accompanist
hey Simon I tested your code on 1.7 HotSpot and it works as you mentioned, if I remove the volatile keyword then Thread1 never finishes, but the strange thing is that if you remove the sleep code that you added before starting T2 then volatile doesn't provide any advantage.Kobold
C
7

The following is a canonical example of the necessity of volatile (in this case for the str variable. Without it, hotspot lifts the access outside the loop (while (str == null)) and run() never terminates. This will happen on most -server JVMs.

public class DelayWrite implements Runnable {
  private String str;
  void setStr(String str) {this.str = str;}

  public void run() {
    while (str == null);
    System.out.println(str);
  }

  public static void main(String[] args) {
    DelayWrite delay = new DelayWrite();
    new Thread(delay).start();
    Thread.sleep(1000);
    delay.setStr("Hello world!!");
  }
}
Costin answered 28/4, 2011 at 22:31 Comment(3)
Wesley: Thank you very much!!! I can see the issue with java -server to start JVM and run the app. Now I get my answer, thanks!Accompanist
new Thread(fun).start(); this line should be new Thread(delay).start(); correct ?Laliberte
Great and useful! I have another questions, 1) Why you use 'canonical '? 2) How could I get the assembly code when the java code is running? can I get some clue from assembly, like other cpp code demonstrations?Pertussis
I
3

Eric, I have read your comments and one in particular strikes me

In fact, I can understand the usage of volatile on the concept level. But for practice, I can't think up the code which has concurrency problems without using volatile

The obvious problem you can have are compiler reorderings, for example the more famous hoisting as mentioned by Simon Nickerson. But let's assume that there will be no reorderings, that comment can be a valid one.

Another issue that volatile resolves are with 64 bit variables (long, double). If you write to a long or a double, it is treated as two separate 32 bit stores. What can happen with a concurrent write is the high 32 of one thread gets written to high 32 bits of the register while another thread writes the low 32 bit. You can then have a long that is neither one or the other.

Also, if you look at the memory section of the JLS you will observe it to be a relaxed memory model.

That means writes may not become visible (can be sitting in a store buffer) for a while. This can lead to stale reads. Now you may say that seems unlikely, and it is, but your program is incorrect and has potential to fail.

If you have an int that you are incrementing for the lifetime of an application and you know (or at least think) the int wont overflow then you don't upgrade it to a long, but it is still possible it can. In the case of a memory visibility issue, if you think it shouldn't effect you, you should know that it still can and can cause errors in your concurrent application that are extremely difficult to identify. Correctness is the reason to use volatile.

Intransitive answered 28/4, 2011 at 14:28 Comment(0)
G
2

The volatile keyword is pretty complex and you need to understand what it does and does not do well before you use it. I recommend reading this language specification section which explains it very well.

They highlight this example:

class Test {
    static volatile int i = 0, j = 0;
    static void one() { i++; j++; }
    static void two() {
        System.out.println("i=" + i + " j=" + j);
    }
}

What this means is that during one() j is never greater than i. However, another Thread running two() might print out a value of j that is much larger than i because let's say two() is running and fetches the value of i. Then one() runs 1000 times. Then the Thread running two finally gets scheduled again and picks up j which is now much larger than the value of i. I think this example perfectly demonstrates the difference between volatile and synchronized - the updates to i and j are volatile which means that the order that they happen in is consistent with the source code. However the two updates happen separately and not atomically so callers may see values that look (to that caller) to be inconsistent.

In a nutshell: Be very careful with volatile!

Grandmamma answered 28/4, 2011 at 10:6 Comment(4)
From the link you provide, an example below: class Test { static volatile int i = 0, j = 0; static void one() { i++; j++; } static void two() { System.out.println("i=" + i + " j=" + j); } } "This allows method one and method two to be executed concurrently, but guarantees that accesses to the shared values for i and j occur exactly as many times, and in exactly the same order, as they appear to occur during execution of the program text by each thread" But I don't think the example is correct, using "volatile' or not has same result, j always has the chance to be different from i.Accompanist
@Eric Jiang - The point is j can be greater than i. Although i is always incremented first. If both are volatile, they can still be different, but j can not be greater than i.Relative
I've updated my answer to explain what i think the JLS is saying (although i think the JLS said it very well in the first place) :)Grandmamma
Thanks alpian, in fact, I can catch your meaning very well, but when I run the code and test for many many times I never see J is greater than i. Is it related to my PC environment, such as JDK version or hardware? Can I understand as that even the code is running for hundreds thousands of times there may be one time that J is greater than i (just has risk but maybe won't happen, so need to use 'volatile' to guarantee), right?Accompanist
S
2

A minimalist example in java 8, if you remove volatile keyword it will never end.

public class VolatileExample {

    private static volatile boolean BOOL = true;

    public static void main(String[] args) throws InterruptedException {
        new Thread(() -> { while (BOOL) { } }).start();
        TimeUnit.MILLISECONDS.sleep(500);
        BOOL = false;
    }
}
Succussion answered 30/10, 2017 at 23:39 Comment(1)
I try your code on android studio, and get the different result. Can you explain why, thxButadiene
L
0

To expand on the answer from @jed-wesley-smith, if you drop this into a new project, take out the volatile keyword from the iterationCount, and run it, it will never stop. Adding the volatile keyword to either str or iterationCount would cause the code to end successfully. I've also noticed that the sleep can't be smaller than 5, using Java 8, but perhaps your mileage may vary with other JVMs / Java versions.

public static class DelayWrite implements Runnable
{
    private String str;
    public volatile int iterationCount = 0;

    void setStr(String str)
    {
        this.str = str;
    }

    public void run()
    {
        while (str == null)
        {
            iterationCount++;
        }
        System.out.println(str + " after " + iterationCount + " iterations.");
    }
}

public static void main(String[] args) throws InterruptedException
{
    System.out.println("This should print 'Hello world!' and exit if str or iterationCount is volatile.");
    DelayWrite delay = new DelayWrite();
    new Thread(delay).start();
    Thread.sleep(5);
    System.out.println("Thread sleep gave the thread " + delay.iterationCount + " iterations.");
    delay.setStr("Hello world!!");
}
Loomis answered 12/11, 2018 at 17:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.