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

when to use volatile java
is volatile atomic in java
volatile keyword in java

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?

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();
  }
}

Interactive Theorem Proving: First International Conference, ITP , This simple rewriting tactic is capable of proving specifications for single passes though code. For example, it can automatically prove the following specification  An irreducible code is a cyclic code in which the code, as an ideal is irreducible, i.e. is minimal in R, so that its check polynomial is an irreducible polynomial. Examples [ edit ] For example, if A = F 2 {\displaystyle \mathbb {F} _{2}} and n =3, the set of codewords contained in cyclic code generated by (1,1,0) is precisely

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!!");
  }
}

The Beauty of Functional Code: Essays Dedicated to Rinus , In fact, one even might say that code written in a functional programming language Sparkle makes it possible to interactively define and prove theorems about examples we want to explore this expected relation between the beauty of the  Two linear codes are equivalentif one can be obtained from the other by a series of operations of the following two types: 1) an arbitrary permutation of the coordinate positions, and 2) in any coordinate position, multiplication by any non-zero scalar. (Note that this second operation preserves the 0 entries.)

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.

The Science of Functional Programming (draft version), If we somehow find a proof tree for a sequent, we can prove the sequent and derive the Here are some examples of using this library for “code inference”. We  If the provider intended to order a chest X-ray, by asking for clarification you can report the service with a more appropriate ICD-9-CM code and eliminate a claim denial. In this example, the arthrocentesis is reported with procedure code 20610 Arthrocentesis, aspiration and/or injection; major joint or bursa (eg, shoulder, hip, knee joint, subacromial bursa) and diagnosis code 719.46 Pain in joint; lower leg.

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!

Covering Codes, Example 3.3.3 We construct an (11,192)1 code. Take first as codewords D In exactly the same way we can prove the following generalization. Theorem 3.4.2  An assertion says that a particular expression always holds when control reaches that part of the code. For example, the following is a trivial use of an assertion inside a dummy method: load in editor. method Testing() {. assert 2 < 3; } Dafny proves this method correct, as 2 is always less than 3.

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;
    }
}

The Dynamics of Interactional Humor: Creating and negotiating , All the examples discussed in the analysis highlight different aspects of in which parental authority can also be managed via the switching of codes (​Examples 6, as teasing can prove an inherently risky conversational activity (​Lytra, 2007). The NFPA National Electrical Code is the most widely used of all the model codes. True Codes and standards set only minimum criteria for design and construction, stricter requirements can be followed.

Pleadings, Parties and Forms Under the Code: Adapted to the , If it could be said that new matter to be specially pleaded, is only an even in some of these instances, for example, where the defense is illegality in the contract, a general denial is sufficient where the plaintifi"s proof will show the illegality,  Your vehicle's key code is usually stored in your owner's manual, as long as it is the one that came with the vehicle when it was new. If not, you will have to prove ownership at a dealership to retrieve the code, which can usually be done for free.

A Treatise on New Trial and Appellate Practice: Presenting and , Special Reference to the Code and Statutes of California, Idaho, Montana, Nevada, ful party can show by the record, or otherwise, that the misconduct had no For example, if a juror is temporarily separated from his fellows, by illness or  In terms of polynomials, computing H r T is the same as evaluating r ( x) at α, andso the above equation can be expressed as. r ( α) = c ( α) + e ( α) = 0 + e ( α) = e ( α). If a single error has occurred, then e has Hamming weight 1 , and e ( x) is a monomial x i for some i, 0 ≤ i ≤ N − 1 .

The Code of Procedure of the State of New York: As Amended to , 756 what will be a waiver of objection 756 uninterrupted absence not necessary 756 example of insufficient proof to exclude the deposition . 746 • executor under will proved abroad 746 who is not an assignee " 747 married women—  For example, if a Mexican company imported fruit from Guatemala, then packed and shipped that fruit to Belgium, the country code portion of the final product’s bar code would likely indicate an

Comments
  • 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.
  • 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.
  • Have a look at this post: stackoverflow.com/questions/7855700/…
  • 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.
  • @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.
  • 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.
  • 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.
  • @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!
  • 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!
  • new Thread(fun).start(); this line should be new Thread(delay).start(); correct ?
  • 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?
  • 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.
  • @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.
  • 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) :)
  • 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?