Discussion on concurrency mechanism of JVM--memory model, memory visibility and instruction reordering

Source: Internet
Author: User
Tags visibility volatile

"Turn" http://my.oschina.net/chihz/blog/58035 article written very good, for the author likes.

Java memory model for our usual development of business applications, memory should be the fastest access to the storage device, for the frequently accessed data, we are always accustomed to put them into the memory cache, a word is not to say, the cache is like a eugenol, where there is a problem to erase. But the CPU is faster than the speed of memory access to a few levels, in order to balance the gap, so specifically for the CPU introduced cache, frequently used data into the cache, the CPU in the use of this data when the operation of the memory does not have to go to access. But in the multi-CPU era, there is a problem, each CPU has its own cache, memory is the common resources shared by all the CPU, so the memory becomes a critical section, if the control is not good for the memory of each CPU concurrent access, then will produce errors, the occurrence of inconsistent data. To avoid this, a cache conformance protocol is required to ensure that there are many such protocols, and that the implementation of each hardware platform and operating system is different.  The JVM needs to implement cross-platform support, which requires a set of its own synchronization protocol to mask the differences between the various underlying hardware and operating systems, thus introducing the Java memory model. For Java developers do not need to care about any hardware details, so there is no concept of multicore CPUs and caches, and the multi-core CPUs and caches in the JVM correspond to the Java language built-in threads and the independent memory space owned by each thread. The Java memory model regulates the synchronization between the data thread's own independent memory space and the JVM's shared memory. The following two graphs illustrate similarities and differences between the hardware platform and the JVM memory model. Figure 1: Hardware platform
Figure 2. Java memory model
    The Java memory model specifies that the variables shared by each thread exist in shared memory (main memories),each thread has its own independent working memory, and the thread can only access its own working memory and cannot access the working memory of the other thread. In working memory, a copy of the main memory shared variable is saved, and the thread is able to manipulate these shared variables, only by manipulating the copy in the working memory, and then synchronizing back to the main memory after the operation is completed. How to guarantee the data integrity of the main memory for multiple threads operation is a challenge, and the Java memory model also defines the protocol for the interaction between working memory and main memory, first defining 8 atomic operations:
(1) Lock: Locks the variable in main memory, which is exclusive to one thread (2) Unclock: Unlocks lock Plus, at which point other threads have the opportunity to access this variable (3) read: Reads the value of the variable in the main memory into the working memory (4) Load: Saves the read read value to a copy of the variable in the working memory. (5) Use: The Code Execution Engine (6) that passes the value to the thread assign: re-assigns the value returned by the execution engine processing to the variable copy (7) Store: Stores the value of the variable copy in main memory. (8) Write: Writes the store stored value to the shared variable of main memory ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + + we can see that to ensure the synchronization of data, lock and unlock define a thread to access a shared memory bounds, there must be a lock operation also has unlock operation, and some operations must be in pairs to appear, such as Read and load, Store and write need to appear in pairs, and if a single instruction is present, then the problem of inconsistent data is caused. The Java memory model also specifies the rules that must be met for these operations: (1) Read and load, store, and write must appear in pairs, do not allow a single operation, or cause values to be read from the main memory, A phenomenon in which the working memory does not accept or the work memory initiates a write operation and the main memory is unacceptable. (2) The assign operation in the thread changes the copy of the variable, then the copy must be synchronized back to main memory via Store-write. If the assign operation does not occur in the thread, then it is not allowed to use Store-write to synchronize to main memory. (3) Load and assign operations must be carried out before the use and store operations are applied to a variable. (4) The variable can only allow one thread to lock it at the same time, and how many times the lock operation must have unlock operation. After the lock operation, the original copy of the variable in working memory is emptied, and the new value needs to be read-load from the main memory again. Before performing the unlock operation, you need to synchronize the changed copy back to main memory. =============================================================================================== memory visibility through the above overview of the Java memory model , we will notice a problem where each thread will operate in its own working memory after acquiring the lockShared variables, where a copy of the working memory is written back to main memory, and the other thread synchronizes the variable back to its own working memory from main memory, the change to the shared variable is not visible to other threads. So many times we need a thread to change the shared variables, and other threads need to know immediately what to do about the change? such as the following scenario, there is a global state variable Open:boolean open= true; This variable is used to describe the open shutdown state for a resource, true to open, false to close, suppose to have a thread A, to modify open to false after doing some action ://thread aresource.close (); open = false; thread B is always interested in the state of open, while Open is true by accessing the resource to do something://thread bwhile (open) {         Dosomethingwithresource (Resource);  } When a resource is closed, the open variable is not visible to thread B. If the change to the open variable is not synchronized to the working memory of thread B at this point, thread B will do something with a resource that has been closed, resulting in an error.
So for the above scenario, a thread is required to change the open, the other threads can be immediately visible, Java provides the volatile keyword, when declaring the open variable, add the volatile keyword to ensure the open memory visibility, That is, open changes are immediately visible to all threads. The principle of volatile guaranteed visibility is a refresh every time a variable is accessed, so each access is the latest version in main memory. =============================================================================================================== ======= Reordering |---Compile-time reordering of compile-time re-ordering is by adjusting the order of instructions, without changing the semantics of the program, as far as possible to reduce the number of registers read, save, fully reuse the memory value of the register. Reordering facilitates the full use of pipelining and enables efficient execution of instructions in parallel. |---Run-time reorder Java memory models in the Java storage model (Java memory model, JMM), reordering is a very important section, especially in concurrent programming. JMM uses the Happens-before law to guarantee sequential execution semantics, and if you want the thread that executes action B to observe the results of the thread that executes action A, then A and B must meet the happens-before principle, otherwise the JVM can sort them arbitrarily to improve program performance. The volatile keyword can guarantee the visibility of a variable, but it does not guarantee its atomicity. Because the operation of volatile is in main memory, the main memory is shared by all threads, which can degrade performance. Volatile modified variables that prevent reordering, discussion of concurrency mechanisms in the JVM-memory model, memory visibility, and command reordering

Discussion on concurrency mechanism of JVM--memory model, memory visibility and instruction reordering

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.