Concurrent Series (ii)----Java memory model

Source: Internet
Author: User

A Brief introduction

In concurrent programming, when two threads (A, b) manipulate a common variable at the same time, thread A will operate the variable when thread B also operates the variable, and thread A is unable to perceive the variable change, causing the variable to change the error. More to the above example, the problem we need to solve is the communication between threads and synchronization. Table in imperative programming, there are two kinds of communication mechanisms between threads: Shared memory and message passing. Java concurrency is a shared-memory model, where communication between Java threads is always implicit, and the entire communication is completely transparent to the programmer.

The abstract structure of the two Java memory models

Communication between Java threads is controlled by the Java memory model (this is referred to as JMM), and JMM determines when a thread's write to a shared variable is visible to another thread. From an abstract point of view, JMM defines the abstract relationship between threads and main memory: Shared variables between threads are stored in main memory, and each thread has a private local memory (local memory) in which the thread is stored in a copy of the read/write shared variable. Local memory is an abstract concept of JMM and is not really there. It covers caching, write buffers, registers, and other hardware and compiler optimizations. The Java memory model is abstracted as follows.


From the point of view, if you want to communicate between thread A and thread B, you have to go through the following 2 steps:

1. First, thread a flushes the updated shared variables in local memory A to the main memory.

2. Then, thread B goes to main memory to read shared variables that have been updated before thread A.

These two steps are described below:


As shown, local memory A and B have a copy of the shared variable x in main memory. Suppose initially, these three in-memory x values are 0. When thread a executes, it temporarily stores the updated X value (assuming a value of 1) in its own local memory a. When thread A and thread B need to communicate, thread a first flushes its local in-memory modified x value to main memory, when the X value in main memory becomes 1. Then, thread B goes to main memory to read the x value of the updated thread A, at which point the X value of the local memory of thread B also becomes 1.

Overall, these two steps are essentially thread a sending a message to thread B, and the communication process must go through main memory. JMM provides a memory visibility guarantee for Java programmers by controlling the interaction between main memory and the local memory of each thread.

Triple sort

In order to improve performance, the compiler and processor often reorder the instructions when executing the program. There are 3 types of reordering.

1. Compiler-Optimized reordering. The compiler can reschedule the execution of a statement without changing the semantics of the single-threaded procedure.

2. Reordering of instruction-level parallelism. Modern processors use instruction-level parallel technology (INSTRUCTION-LEVELPARALLELISM,ILP) to overlap multiple instructions. If there is no data dependency, the processor can change the order in which the statement corresponds to the machine instruction execution.

3. Reorder the memory systems. Because the processor uses the cache and read/write buffers, this makes the load and storage operations appear to be in a disorderly sequence

From the Java source code to the final actual execution of the sequence of instructions, the following three kinds of reordering are experienced:


The above 1 belongs to the compiler reordering, and 2 and 3 are processor reordering. These reordering may cause memory visibility issues with multithreaded programs. For compilers, the compiler-JMM of a compiler prevents a particular type of compiler from being reordered (not all compilers are forbidden). For processor reordering, the JMM collation of the handler will require the Java compiler to insert a specific type of memory barrier when generating the sequence of instructions (memories Barriers,intel called the Fence) instruction, A memory barrier directive prevents a particular type of handler from being reordered. JMM is a language-level memory model that ensures that programmers are guaranteed consistent memory visibility over different compilers and different processor platforms by prohibiting certain types of compilers from reordering and processing.

To ensure memory visibility, the Java compiler inserts a memory barrier directive in place of the generated instruction sequence to suppress a particular type of handler reordering. JMM the memory barrier directive into 4 categories


Four Happens-before

JSR-133 presents the concept of Happens-before, which illustrates the memory visibility between operations. If the result of one operation needs to be visible to another, there must be a happens-before relationship between the two operations. The two actions mentioned here can be either within a thread or between different threads. The Happens-before rules that are closely related to programmers are as follows:

1. Program Order rules: Each action in a thread is happens-before to any subsequent action in that thread.

2. Monitor lock rule: Unlocks a lock, happens-before to the subsequent locking of the lock.

3. Volatile variable rule: write to a volatile field, happens-before to any subsequent read of this volatile field

4. Transitivity: If a happens-before B, and B happens-before C, then a Happens-before c.

Note: There is a happens-before relationship between the two operations, which does not mean that the previous operation must be performed before the next operation! Happens-before only requires that the previous operation (the result of execution) be visible to the latter operation, and that the previous operation precedes the second operation in order

5.start () rule: If thread A performs an operation Threadb.start () (boot thread B), then a thread threadb.start () operation Happens-before Any action in thread B.

6.join () rule: If thread A performs an operation Threadb.join () and returns successfully, any happens-before in thread B is returned successfully from the Threadb.join () operation of Thread A

The relationship between Happens-before and JMM is as follows:


As shown, a Happens-before rule typically corresponds to multiple compiler collation and handler reordering rules. For Java programmers, the Happens-before rules are easy to understand, avoiding the programmer to learn complex reordering rules and the specific implementations of these rules in order to understand the memory visibility that JMM provides

Five notes

As long as the memory model can not escape Cheng write memory in-depth understanding of the Java memory model, I was reading his "Deep Java memory Model" wrote that would like to make a summary of the results summed down found 90% or book. I have limited ability to write something that I think is more useful in understanding Java's memory model. There is a Cheng blog address in the reference document.

In-depth understanding of the Java memory Model (i)--basic

Concurrent Series (ii)----Java memory model

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.