Java Memory Model Knowledge Point Summary---"in-depth understanding of Java memory Model" (Cheng) Reading summary

Source: Internet
Author: User

One, the Java memory model describes the scope of the memory model:

In Java, all instance fields, static fields, and array elements are stored in heap memory, shared among threads, and referred to as "shared variables". Local variables, method parameters, exception handlers, etc. are not shared between threads, there is no memory visibility issue, and are not affected by the memory model.

Reordering and Visibility:

The modern compiler will do some optimizations when compiling the source code, and re-order the codes, and the modern pipeline structure of the processor in order to improve the degree of parallelism, in the execution of the instructions may also be made in order to adjust. Reordering includes compiler reordering, instruction-level parallel reordering, and memory system reordering. In general, compilers and processors make some guarantees when reordering, guaranteeing that the execution of the program is the same as the execution of the command before reordering. That is, as-if-serial, regardless of reordering, can not change the execution results of the program.

The CPU typically uses caching techniques to improve efficiency when executing instructions, and if different threads use different cache space, it can cause one thread to update a shared variable without being reflected to other threads in time, that is, the problem of multi-threaded visibility of shared variable updates is very complex.

Abstraction of the Java memory model:

For the above problem, the Java memory Model (JMM) provides an abstract level of description for programmers, we do not have to care about the compiler, the processor how to reorder the instructions, do not care about the complex system caching mechanism, as long as follow the JMM rules, JMM can provide us with code order, The guarantee of shared variable visibility, resulting in the expected execution results.

JMM determines when a thread's write to a shared variable is visible to another thread. In abstract terms, thread-shared variables are stored in main memory (main memories), each thread holds a local memory (local memory), and a copy of the thread's read-write shared variable is stored locally (local memory is an abstract concept of JMM, not real). Such as:

If a, b two threads want to communicate to go through the following two steps: First, thread A flushes the locally-in-memory updated shared variables into main memory, then thread B to main memory reads a variable that was updated before a.

JMM provides visibility guarantees for Java programmers by controlling the interaction between main memory and the local memory of each thread.

Re-order:

The modern compiler and processor reorder the order in which the instructions are executed, improving the performance of the program. These reordering may cause memory visibility issues with multithreaded programs. In order not to change the execution result of the program, JMM suppresses certain types of compilers for the compiler, and for processor reordering, JMM requires inserting a specific type of memory barrier when compiling the production instruction sequence in Java, which suppresses the reordering of certain types.

JMM divides the memory barrier into the following four categories:

barrier type instruction example description
loadload barriers Ensure that the LOAD1 data is loaded before the Load2 and all subsequent load instructions
storestore barriers ensure Store1 and Store2 and subsequent storage instructions
loadstore Barriers Ensure LOAD1 data is loaded prior to Store2 and subsequent storage instructions
storeload Barriers

Ensures that Store1 refreshes data to memory before Load2 and its subsequent load instructions. The

Storeload barriers causes all memory access instructions before the barrier to complete before the barrier instruction is executed.

The Storeload barriers is an all-purpose barrier, with the effect of three other barriers.

Happens-before:

Starting with JDK1.5, Java uses the new JSR-133 memory model (all of the following are for this memory model), using the concept of Happens-before to illustrate the memory visibility between operations.

If an operation is to be visible to another operation, the happens-before relationship must exist between the two operations. Both of these operations can be within a thread or between different threads. PS. (Two operations the presence of a happens-before relationship does not imply that the previous operation must be performed before the latter operation, only requiring the previous operation to be visible to the latter operation. )

Common programmer-related Happens-before rules are as follows:

① program sequence rules: Each action in a thread happens-before any subsequent action;

② Monitor Lock rule: the unlocking of a monitor is happens-before to the locking of the monitor subsequently;

③volatile rule: Write Happens-before of a volatile field to any subsequent read operations on the domain (the rule is also established between multiple threads);

④ transitivity: If a happens-before B, and B happens-before C, then a happens-before c

Data dependencies: If two operations access the same variable, and one of the two operations is a write operation, there is a data dependency between the two operations. The following example:

Read after writing

A=1;

B=a;

Write and write after

A=1;

a=2;

Write after reading

A=b;

B=a;

There are data dependencies in the three categories above, where reordering is not allowed, or the results of the program may change.

As-if-serial semantics:

As-if-serial semantics means: In a single thread, no matter how it is reordered, the execution of the program does not change, in the programmer's view, like sequential execution.

Example:

A = 1; //a
B = 2 ; //b
C = a + B; //c

The first two statements can be reordered, and the third statement has dependencies on the first two and cannot be reordered.

The above a happens-before b,b happens-before C, but does not guarantee that a is performed before B, just make sure that operation A is visible to B (a operation here does not need to be visible to B, so it can be re-queued)

Effects of reordering on multithreading:

Example:

classDemo {
Booleanflag = false;
intA =0;

Public voidfun1 () {
A =
1; //a
flag = true;//b
    }

Public voidfun2 () {
if(flag) {C
A = a + A;//d
        }
}
}

Assuming that fun1 () and fun2 () in the above classes are executed in different threads, operations A and B do not have dependencies and may be reordered; Operation C, D although there is a control dependency, modern compilers and processors in order to improve parallelism, it is possible to take a radical approach (that is, the value in the IF statement block is stored in the temporary variable, If the IF condition is true then the value is used, otherwise discarded) to reorder it, which can change the execution result of the program.

Sequential consistent memory model:

Computer scientists have proposed an idealized theoretical reference model-the sequential consistency model, which provides the programmer with very strong memory visibility with the following two features:

① all operations in a single thread must be executed in the order of the program;

② all threads, whether synchronous or not, can see only a single sequence of operations execution. Each operation must be atomic and immediately visible to all threads.

Example:

Assuming that A and b two threads execute concurrently, there are three operations in the a thread, the order is A1->A2->A3, and thread B has three operations in the order of B1->B2->B3. Assuming that these two threads use monitor synchronization, a-line enters upgradeable obtains the monitor, and thread B begins execution after the release monitor is finished. Then they perform the following effects in the sequential consistency model:

Now let's assume that these two threads are not synchronized, and that they perform in the sequential consistency model as follows:

As you can see, programs that are not synchronized are in the sequential consistency model, although the overall order of execution is unordered, but all threads see only a consistent overall order of execution. For example, threads A and b see the order of execution as B1->A1->A2->B2-A3->B3. This guarantee is achieved because each operation in the sequential consistent memory model must be immediately visible to any thread.

But there is no such guarantee in JMM. For example, the current thread writes data to local memory, the write operation is only visible to the current thread until it has been flushed to the main memory, and viewed from other threads, it can be assumed that the write operation has not been executed by the current thread at all. In this case, the execution order of the operations that the current thread and other threads see will be inconsistent.

The consistency effect of the synchronization program:

Example:

classSynchronizeddemo {
intA =0;
BooleanFlag = false;
Public synchronized voidWrite () {
A =
1;
Flag = true;
}

Public synchronized voidRead () {
if(flag) {
inti = A;
}
}
}

The above code uses the synchronous method, thread a first executes the write () method, and after releasing the lock, thread B acquires the lock and executes the read () method, which executes the following process:

In the sequential consistency model, all operations are performed sequentially. In JMM, the code in the critical section can be reordered (JMM does not allow the code in the critical section to "Escape" beyond the critical section), and JMM will make some restrictions on the key points in the entry and exit critical sections, making the field have the same memory view as the sequential consistency model at these two key points. Although field A is reordered in the critical section, because of the mutual exclusion of the monitor, thread B simply cannot "observe" the reordering of thread A in the critical section, which improves efficiency without changing the execution result of the program.

For unsynchronized multithreaded programs, JMM only provides minimal security: the value that the thread takes to perform the read operation, either the front-line write or the default (0,null,false), JMM guarantees that the data read by the thread is not out of the way. For minimal security, the JVM first empties the memory space when allocating objects on the heap, and then allocates the object (so that the default initialization of the domain is complete when the object is allocated).

In addition, the minimum security of the JMM does not guarantee that the read and write of the 64-bit long and double variables are atomic, while the sequential consistency model guarantees atomicity for all memory read-write operations.

Second, volatile characteristics

A single read/write of a volatile variable is equivalent to using a lock to synchronize these individual reads/writes.

atomicity : A single read and write operation on volatile variables is atomic (Ps. There is a controversy here, for the time being, to write, to retain opinions);

Visibility : The Happens-before rule of the lock guarantees the visibility between the release lock and the two threads that get the lock, which means that a read operation on a volatile variable always sees the last write to the volatile variable by any thread. That is, write operations on volatile variables are immediately visible to other threads.

When writing a volatile variable, JMM flushes the shared variables in the local memory of the thread to the main memory;

When reading a volatile variable, JMM will change the local memory corresponding to the nickname to invalid, then read the value of the shared variable from the main memory.

From the memory semantics point of view, the release of volatile write-read Yu Yu-get has the same memory effect. Therefore, if thread a writes to a volatile variable, it has a happens-before relationship before threads B reads the volatile variable.

Example:

 class   Volatiledemo { volatile  boolean  flag = false  Span style= "color: #000000;"      >;  int  a=0 
 public  void   Fun1 () {a  = 1; // a  flag = true ; // b      Fun2 () { if  (flag) {// c  a=a+a; // d   

The above operation a happens-before operation B, Operation C Happens-before operation D, if thread 1 calls the fun1 () method after thread 2 calls the fun2 () method , then the operation B Happens-before operation C, according to the Happens-before of the transitivity, there is a happens-before D, Therefore, the operation D can be guaranteed to read the assignment of operation a correctly.

Volatile memory semantics is jmm by inserting a memory barrier before and after volatile read and write operations.

Three, the characteristics of the lock

The release and acquisition of the lock follows the Happens-before rule, releasing the operation result of the lock thread critical section visible to the thread that acquires the lock.

When the thread releases the lock, JMM flushes the shared variables in the local memory of the thread to the main memory;

When a thread acquires a lock, JMM resets the local memory corresponding to the nickname to invalid, and then reads the value of the shared variable from main memory.

Reentrantlock is the implementation of a lock under the Java.util.concurrent.locks package, which relies on the read-write and Compareandset (CAS) operation of the volatile variable to implement the lock mechanism. CAS operations use different CPU instructions to achieve atomicity of a single operation, with the same memory semantics as volatile read and write operations. The class diagram is as follows:

Reentrantlock according to the thread of preemption lock processing way, divided into fair lock and non-fair lock, first look at the fair lock, the use of fair lock plus Lock, lock method Lock () method call mainly has the following four steps:

123. Abstractqueuedsynchronizer:acquire (int4. Reentrantlock:tryacquire (int acquires)

In the fourth step only to start the real lock, the method of the source code is as follows:

protected Final BooleanTryacquire (intacquires) {            FinalThread current =Thread.CurrentThread (); intc =getState ();();//Gets the start of the lock, State is the volatile type variable              if(c = = 0) {                if(!hasqueuedpredecessors () &&Compareandsetstate (0, acquires))                    {Setexclusiveownerthread (current); return true; }            }            Else if(Current = =Getexclusiveownerthread ()) {                intNEXTC = C +acquires; if(NEXTC < 0)                    Throw NewError ("Maximum Lock count Exceeded");                SetState (NEXTC); return true; }            return false; }

As can be seen from the above method, the lock method first reads the volatile variable state.

The unlock () method call path using the Fair lock is as follows:

12. Abstractqueuedsynchronizer:release (int3. Sync:tryrelease (int releases)

In the third step of the call to really start the release of the lock, the source of the method is as follows:

protected Final BooleanTryrelease (intreleases) {    intc = getState ()-releases; if(Thread.CurrentThread ()! =Getexclusiveownerthread ())Throw Newillegalmonitorstateexception (); BooleanFree =false ; if(c = = 0) { free=true ; Setexclusiveownerthread (NULL ); } setState (c);//after releasing the lock, write the volatile variable state    returnFree ;}

As can be seen from the above code, at the end of the release lock write the volatile variable state.

The fair lock writes the volatile variable state at the end of the release lock and reads the volatile variable first when acquiring the lock. According to the volatile Happens-before rule, the thread releasing the lock is visible to the thread that acquires the lock after the volatile variable is written.

CAS operations in Java have both volatile read and volatile write memory semantics, so there are four ways to communicate between Java threads:

1, a thread writes the volatile variable, and then the B thread reads the volatile variable.

2, a thread writes the volatile variable, and then the B thread updates the volatile variable with CAs.

3, a thread updates a volatile variable with CAS, and then the B thread updates the volatile variable with CAs.

4, a thread updates a volatile variable with CAS, and then the B thread reads the volatile variable. A thread Write

The CAs in Java use the high-efficiency machine-level atomic instructions available on modern processors that atomically perform read-and-write operations on memory, while the read/write and CAs for volatile variables can communicate between threads. The integration of these features forms the cornerstone of the entire concurrent package. If we carefully analyze the source code implementation of the concurrent package, we will find a generalized implementation pattern:

1. First, declare the shared variable to be volatile;

2, then, the use of CAS atomic condition update to achieve synchronization between threads;

3, at the same time, with volatile read/write and the CAS has the volatile read and write memory semantics to achieve the communication between the threads.

Iv. Characteristics of Final

Compared to the lock and volatile described earlier, the read and write to the final domain is more like normal variable access. For the final domain, the compiler and processor are subject to two (read-write) reordering rules:

1, write to a final field within the constructor, and then assign a reference to the referenced variable, which cannot be reordered between the two operations.

2. First read a reference to an object that contains a final field, and the final field is then first read, and cannot be reordered between the two operations.

Write final field reordering rules

A reorder rule that writes a final field prevents the final field from being sorted out of the constructor. The implementation of this rule consists of the following 2 aspects:

1. JMM prohibits the compiler from ordering the final field's write-back to a constructor function.

2. The compiler inserts a storestore barrier before the constructor return after the final field is written. This barrier prohibits the processor from ordering the final domain's write-back to the constructor.

The collation of the final field ensures that the final domain of the object has been properly initialized before the object reference is visible to any thread, and the normal domain does not have this guarantee

For reference types, the reorder rules for the write final domain add the following constraints to the compiler and processor:

Writes to a member field of a final referenced object within a constructor, and then assigns a reference to a reference variable outside of the constructor to the constructed object, and cannot be reordered between the two operations.

Read the Reorder rules for final fields

In one thread, the first read object reference and the first read of the object contains the final domain, JMM prohibit the processor reordering these two operations (note that this rule is only for the processor). The compiler inserts a loadload barrier before the read final domain operation. An indirect dependency exists between the first-read object reference and the first-read final domain that the object contains. Because the compiler adheres to indirect dependencies, the compiler does not reorder the two operations.

Reading the collation of the final field ensures that a reference to the object containing the final field must be read before the final field of an object is read. In this example program, if the reference is not NULL, then the final domain of the referencing object must have been initialized by a thread.

Java Memory Model Knowledge Point Summary---"in-depth understanding of Java memory Model" (Cheng) Reading summary

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.