What does “volatile” mean in Java?

后端 未结 6 1691
盖世英雄少女心
盖世英雄少女心 2020-11-29 08:14

We use volatile in one of our projects to maintain the same copy of variable accessed by different threads. My question is whether it is alright to use vo

相关标签:
6条回答
  • 2020-11-29 08:34

    In Java, volatile has a similar general meaning as it does in C. The Java Memory Model (see the excellent link in ide's answer) allows threads to "see" a different value at the same time for variables marked as non-volatile. For example:

    Thread a:

    n = 1;
    // wait...
    n = 2;
    

    Threads B and C:

    while (true) {
        System.out.println(name + ": " + n);
    }
    

    This output is allowed to happen (note that you're not guaranteed to strictly alternate between B and C, I'm just trying to show the "changeover" of B and C here):

    C: 1
    B: 1
    C: 2
    B: 1
    C: 2
    B: 2
    

    This is entirely separate from the lock taken by println; thread B is allowed to see n as 1 even after C finds out that it's 2. There are a variety of very good reasons for this that I can't pretend to fully understand, many pertaining to speed, and some pertaining to security.

    If it's volatile, you're guaranteed (apart from the println's locking, which I'll ignore for the moment) that B and C will both "simultaneously" see the new value of B as soon as it is sent.

    You can use volatile with static because they affect different things. volatile causes changes a variable to be "replicated" to all threads that use that variable before they use it, while static shares a single variable across all classes that use that variable. (This can be rather confusing to people new to threading in Java, because every Thread happens to be implemented as a class.)

    0 讨论(0)
  • 2020-11-29 08:35

    Consider a scenario when two thread (Thread1 and Thread2) are accessing same variable 'mObject' with value 1.

    when a Thread1 runs, it doesn't expect other threads to modify the variable 'mObject'. In this scenario the Thread1 caches the variable 'mObject' with value 1.

    And if the Thread2 modify the value of 'mObject' to 2, still the Thread1 would be refering the mObject value as 1 since it did caching. To avoid this caching we should to declare the variable as

    private volatile int mObject;

    in this scenarion the Thread1 will be getting updated value of mObject

    0 讨论(0)
  • 2020-11-29 08:37

    Small elaboration, but the volatile keyword isn't just for for memory visibility. Before Java ver 1.5 was released the volatile keyword declared that the field will get the most recent value of the object by hitting main memory each time for reads and flushing for writes.

    In the latest Java versions, the volatile keyword says two very important things:

    1. Don't worry about how but know that when reading a volatile field you will always have the most up to date value.
    2. A compiler cannot reorder a volatile read/write as to maintain program order.

    Check it out for more Java volatile examples.

    0 讨论(0)
  • 2020-11-29 08:58

    Volatile is used in many different situations where multiple threads need access to the same variable. Many people not doing multi-threaded/concurrent programming would not be exposed to this. Volatile ensures that the variable is always read from main memory and not from a cache/register version. Volatile is not itself a lock, just because the changes are seen by all threads as soon as they are written does not mean that you can compare and swap in an atomic way. However this feature can be used with other features, like compare-and-swap to build data structures that are thread safe without requiring the user of java's wait-notify semantics which are "heavier".

    you can get more info on this link http://www.quora.com/Threading-in-Java/What-is-the-purpose-of-the-volatile-keyword-in-java

    0 讨论(0)
  • 2020-11-29 08:59

    volatile means that the variable changes at runtime and that the compiler should not cache its value for any reason.

    This is only really a problem when sharing the variable amongst threads, you don't want a thread working with stale data, so the compiler should never cache the value of a volatile variable reference.

    0 讨论(0)
  • 2020-11-29 09:00

    Short of reading the memory model specification, I recommend you read http://jeremymanson.blogspot.com/2008/11/what-volatile-means-in-java.html. It's written by one of the JMM authors and should answer your question. Thinking of memory reads and writes in terms of the happens-before clause is also helpful; the JMM for Java 5 onwards adds happens-before semantics to volatile.

    Specifically, when you read a volatile variable from one thread, all writes up to and including the write to that volatile variable from other threads are now visible to that one thread. If you have some time, there's a Google tech talk that further discusses the topic: https://code.google.com/edu/languages/#_java_memmodel.

    And, yes, you can use static with volatile. They do different things.

    0 讨论(0)
提交回复
热议问题