Volatile in Java

Source: Internet
Author: User

Visibility of:

Visibility is a complex property, because errors in visibility always violate our intuition. In general, we cannot ensure that threads that perform read operations can see the values written by other threads in a timely fashion, sometimes even impossible. In order to ensure the visibility of memory write operations between multiple threads, the synchronization mechanism must be used.

  visibility refers to the visibility between threads, and the state of one thread modification is visible to another thread. that is, the result of a thread modification. Another thread can see it right away. For example: variables modified with volatile will have visibility. Volatile-modified variables do not allow the thread to cache and reorder internally, that is, to modify memory directly. So it is visible to other threads. But there is a problem to be aware of, and volatile can only make it visible to the content he modifies, but it does not guarantee that it is atomic. For example, volatile int a = 0, then there is an operation a++, this variable a has visibility, but a++ is still a non-atomic operation, that is, the operation also has a thread safety problem.

Atomic nature:

  atoms are the smallest units in the world and are indivisible. such as a=0; (a non-long and double type) This operation is indivisible, then we say this operation is atomic operation. Another example: a++; This operation is actually a = a + 1; is divisible, so he is not an atomic operation. There is a thread-safety problem with non-atomic operations, and we need to use synchronous technology (sychronized) to turn it into an atomic operation. An operation is an atomic operation, so we call it atomic. The Java concurrent package provides some atomic classes, and we can read the API to understand the use of these atomic classes. For example: Atomicinteger, Atomiclong, atomicreference and so on.

The following section of code in a multithreaded environment, there will be problems.

+ View Code
1/** 2  * @author zhengbinmac 3 */  4 public class Novisibility {5     private static Boolean ready; 6     Private static int number; 7     private Static class Readerthread extends Thread {8         @Override 9 public         void Run () {Ten while             (!ready) {11                 Thread.yield ();             System.out.println (number);         }15}16 public     static void Main (string[] args) {         new Readerthread (). Start (); number         = 42;19 ready         = true;20     }21}

Novisibility may continue to cycle because the read thread may never see the value of ready. Even novisibility may output 0, because a read thread might see a value written to ready, but it does not see a value written to number after that, which is called "reordering." As long as the reordering condition cannot be detected in a thread (even if the reordering in the thread is visible in other threads), there is no way to ensure that the operations in the thread are executed in the order specified in the program. When the main thread first writes number and then writes to ready without synchronization, the read thread may see the exact reverse order of the write.

In the absence of synchronization, the compiler, the processor, and the runtime can make some unexpected adjustments to the order in which the operations are executed. In the absence of sufficient synchronization of multi-threaded programs, to the memory operation of the implementation of Spring Xu judgment, can not get the correct conclusion.

This looks like a failed design, but it allows the JVM to take full advantage of the power of modern multicore processors. For example, in the absence of synchronization, the Java memory model allows the compiler to reorder the order of operations and cache the values in registers. In addition, it allows the CPU to reorder the order of operations and cache the values in the processor-specific cache.

Second, the volatile principle

The Java language provides a slightly weaker synchronization mechanism, the volatile variable, that is used to ensure that updates to variables are notified to other threads. When a variable is declared as a volatile type, the compiler and the runtime will notice that the variable is shared, so the operation on that variable is not reordered with other memory operations. Volatile variables are not cached in registers or in places that are not visible to other processors, so the most recent write value is always returned when reading a variable of type volatile.

The volatile variable is a more lightweight synchronization mechanism than the Sychronized keyword, because it does not perform a lock operation when accessing a volatile variable, and therefore does not cause the execution thread to block.

When reading and writing non-volatile variables, each thread first copies variables from memory to the CPU cache. If the computer has multiple CPUs, each thread may be processed on a different CPU, which means that each thread can be copied to a different CPU cache.

While declaring variables to be volatile, the JVM guarantees that each read variable is read from memory, skipping the CPU cache step.

When a variable is defined as volatile, there are two characteristics:

1. Ensure that this variable is visible to all threads, where the "visibility", as described at the beginning of this article, when a thread modifies the value of this variable, the new value is immediately known to other threads. But ordinary variables do not do this, the value of the normal variable between the thread pass through the main memory (see: Java memory Model) to complete.

2. Prohibit command reordering optimization. A variable with a volatile modifier, after which the assignment performs a "Load Addl $0x0, (%ESP)" operation, which is equivalent to a memory barrier (the command reordering cannot reorder the subsequent instructions to the memory barrier), Memory barriers are not required when only one CPU accesses memory; (What is command reordering: refers to the CPU used to allow multiple instructions not in accordance with the program specified in the order of development to each corresponding Circuit unit processing).

Volatile in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.