Java multi-thread volatile explanation

Source: Internet
Author: User
Tags volatile

Java multi-thread volatile explanation

?? Recently has been looking at some of the multi-threading knowledge, read some books and some blog, harvest or a lot of, recently read the "Java Concurrent programming Art" This book feels great Harvest is also recommended to you, but also combined with the blog before the good summary of what you learn, there are insufficient places to welcome you to correct, This article is mainly about the knowledge of the volatile keyword.

Characteristics of volatile
    • Visibility: Volatile can guarantee the "visibility" of shared variables in multiple threads, simply because when a thread modifies a volatile variable, the Java thread memory model ensures that the value of the variable that all threads see is consistent.
    • Prevent command reordering
Java memory model
    • Before learning about the volatile knowledge, let's start with a simple understanding of the Java Memory Model (JMM) reference a very classic diagram of the Java memory model on the Web

    • Probably explaining the meaning of the figure.
      • When multiple threads are running, each thread has a memory space of its own
      • Multiple threads working together with one main memory
      • Each thread gets the relevant data in main memory before making changes to the data, and then operates on the data in its own working RAM.

        Visibility of

        The key is here, because each thread Cheng ran in its own memory, but the working memory of each is invisible to each other, so modifications to shared variables are not immediately visible to other threads, so it causes multiple threads to manipulate the same data, but the final result is not the result we expect. When thread 1 goes first to load a volatile variable from main memory into its own work, and then writes the volatile variable, the latest value of the volatile variable is flushed to the main memory immediately after the write operation is completed. At the same time, this volatile variable in other threads will be invalidated immediately and will be forced to reread the latest value of the volatile variable from main memory, which is the process of realizing the visibility of the volatile variable. This can also be seen as a process of communication between a thread and other threads.

        Prevent command reordering

        A simple explanation of the order reordering, reordering refers to the compiler and the processor in order to optimize the performance of the program to reorder the instruction sequence of a means. In a single-threaded program, the reordering of instructions guarantees the correctness of the execution results, but the reordering of instructions in multi-threading will not guarantee the correctness of the results of the execution of the program (some rules of order reordering can be consulted, not described here). Volatile variables prevent command reordering please look at the following memory barrier introduction first. (In fact, synchronized also have some restrictions on the reordering of instructions, I will write an explanation of the synchronized Boven detailed explanation, welcome to read)

Memory barrier

JMM the memory barrier into four classes (excerpt from Java Concurrent programming art)
| Barrier Type | instruction Example | Description |
| ----------------- |:-------------:| -----:|
| Loadload Barriers | Loadl; Loadload; Load2 | Ensure that LOADL data is loaded prior to Load2 and all subsequent load instructions |
| Storestore Barriers | Storel; Storestore; Store2 | Ensure that Store1 data is visible to other processors (flushed to memory) prior to Store2 and all subsequent storage instructions |
| Loadstore Barriers | Loadl; Loadstore; Store2 | Ensure that LOADL data is loaded before Store2 and all subsequent storage instructions are flushed to memory |
| Storeload Barriers | Storel; Storeload; Load2 | Make sure that the Storel data becomes visible to other processors (that is, flush to memory) before Load2 and all subsequent mount instructions. Storeload barriers will make all memory access instructions before the barrier (store and mount instructions) complete before executing the memory Access command after the Barrier |

    • Volatile variable JMM memory barrier insertion strategy based on conservative policy
      • Insert a storestore barrier in front of each volatile write operation.
      • Insert a storeload barrier behind each volatile write operation.
      • Insert a loadload barrier behind each volatile read operation.
      • Insert a loadstore barrier behind each volatile read operation.

After reading this, I believe you have a clear understanding of the volatile prevention Command reordering, explain the above four strategies,

    • Other writes preceding the write operation of the volatile variable are executed before the volatile variable write (flushed to main memory, visible to other threads)
    • Volatile variables are written more advanced than other read and write operations.
    • The read operation before the volatile variable read operation is performed before the volatile variable read operation
    • Other writes after the volatile variable read operation are performed after the volatile variable read operation

      Application of Volatile

      Many blogs have basically said that volatile variables are generally applied to operations that do not adhere to the current value, such as self-increment, as my understanding is, if the volatile variable carries the operation of the value attached to the current operation, Then it involves reading both the volatile variable and the write volatile variable, the read operation of the volatile variable (from the main memory read to the working memory of the thread) and the write operation (to write the variable into the main memory), the combination of the two operations is a non-atomic operation, So it is inappropriate to use the volatile keyword in this case, and for some non-atomic operations of basic variables (such as self-increment) you might consider using some classes under the Java.util.concurrent.atomic package, or using locks. Volatile variables are generally used as a single read-write operation such as a flag variable.
      Attach a well-spoken blog (https://www.ibm.com/developerworks/cn/java/j-jtp06197.html) that individuals feel the use of volatile variables
      At the same time you can also go to see another article on the volatile blog, also relatively good (http://kwsir.cn/2017/10/12/Java%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8% 8b-volatile%e5%8f%af%e8%a7%81%e6%80%a7%e7%9a%84%e4%bb%8b%e7%bb%8d/).

Written in the last

In view of my limited level, so if the article has the wrong place, very welcome you in comment message pointing, or send to my QQ mailbox [email protected] notice me. Thank you.

Java multi-thread volatile explanation

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.