1. Overview
Multitasking and high concurrency are one of the most important indicators of the ability to measure a computer's processor. A general measure of the performance of a server, the use of transactions per second (transactions per Second,tps) This indicator comparison can explain the problem, it represents the average number of servers in a second to respond to requests, and the TPS value and program concurrency is very closely related. Before discussing the Java memory model and threading, let's briefly describe the efficiency and consistency of the hardware.
2. The efficiency and consistency of the hardware
Since there are several orders of magnitude difference between the computer's storage device and the processor's computing power, modern computer systems have to add a cache of read-write speeds as close as possible to the processor's operating speed as a buffer between memory and processor: the data to be used for the operation is copied to the cache. So that the operation can be done quickly, when the operation is finished and then synchronized back to the memory from the cache without waiting for slow memory to read and write.
Cache-based storage interaction solves the contradiction between processor and memory speed, but introduces a new problem: Cache consistency (Coherence). In multiprocessor systems, each processor has its own cache, and they share the same main memory, as shown in: Multiple processor operations involve the same piece of main memory, requiring a protocol that guarantees data consistency, such as MSI, MESI, Mosi, and Dragon protocol. The memory access operations defined in the Java Virtual Machine memory model are comparable to the cache access operations of the hardware, and the Java memory model is described later.
In addition, in order to allow the processor inside the operating unit can be fully utilized, the processor may be in the input code execution (Out-of-order execution) optimization, the processor will be after the calculation of the disorderly execution of the code to reorganize the results to ensure the accuracy of the results. Similar to the processor's unordered execution optimizations, the Java Virtual machine's instant compiler also has similar command reordering (instruction Recorder) optimizations.
3.Java in-memory model (Java memory model,jmm)
Defining the Java memory model is not an easy task, and the model must be sufficiently rigorous to make Java's concurrent memory access Operations unambiguous, but it must also be sufficiently loosely defined. The implementation of the virtual machine can have enough free space to take advantage of the various features of the hardware (registers, caches, etc.) to obtain better execution speed. After a long period of validation and patching, the Java memory model has matured and perfected after JDK1.5 was released.
3.1 main memory vs. working memory
The main goal of the Java memory model is to define access rules for variables in the program, that is, the underlying details of storing variables into memory and removing variables from memory in the virtual machine. The variables here are different from those described in Java programming, including only instance fields, static fields, and elements that make up the array object, but not local variables and method parameters, which are thread-private and not shared, and there is no problem of competition.
The Java memory model specifies that all variables are stored in the main memory (main memories), each thread also has its own working memory (working memories) (which can be compared to the cache analogy of the previous processor), and the working memory of the thread is stored in the the main memory copy of the variable used by the thread, all operations of the thread on the variable (read, assign) must be made in working memory, not directly read and write to the variables in main memory. Variables in the other's working memory cannot be accessed directly between threads, and the transfer of variable values between threads needs to be done through main memory, with threads, main memory, and working memory interacting as shown, and very similar.
The main memory, the working memory, and the Java heap, stack, and method area of the Java memory area are not the same level of memory partitioning.
3.2 Inter-memory interoperability
The Java memory model defines the following 8 actions for the specific interaction protocol between main memory and working memory, that is, how a variable is copied from main memory to working memory, how to synchronize from working memory to main memory.
- Lock: A variable that acts on the main memory and identifies a variable as a thread-exclusive state.
- Unlock (Unlocked): Acts on the main memory variable, releasing a variable that is in a locked state, and the released variable can be locked by another thread.
- READ: Acts on the main memory variable, transferring a variable value from main memory to the working memory of the thread for subsequent load actions to use
- Load: A variable that acts on working memory, which places the value of a read operation from the main memory into a variable copy of the working memory.
- Use: A variable that acts on the working memory, passing a variable value in the working memory to the execution engine , which is performed whenever the virtual opportunity is to a bytecode instruction that needs to use the value of the variable.
- Assign (Assignment): A variable acting on a working memory that assigns a value to a working memory from the execution engine , and performs this operation whenever the virtual opportunity is assigned to a byte-code instruction that assigns a value to a variable.
- Store: A variable acting on a working memory that transfers the value of a variable in the working memory to the main memory for subsequent write operations.
- Write: A variable that acts on the main memory, which transfers the store operation from the value of a variable in the working memory to a variable in the main memory.
If you want to copy a variable from main memory to working memory, you need to perform the read and load operations sequentially, and if you synchronize the variables from the working memory back to main memory, store and write operations are performed sequentially. The Java memory model only requires that the above operations must be executed sequentially, without guarantee that continuous execution is required. That is, between read and load, the store and write can be inserted between the other instructions, such as the main memory of the variable A, b access, the possible order is read A,read B,load b, load a. The Java memory model also stipulates that when performing the eight basic operations above, the following rules must be met:
- Does not allow one of the read and load, store, and write operations to appear separately
- A thread is not allowed to discard its most recent assign operation, that is, the variable must be synchronized to main memory after it has changed in working memory.
- A thread is not allowed to synchronize data from the working memory back to main memory for no reason (no assign operation has occurred).
- A new variable can only be born in main memory, and it is not allowed to use a variable that is not initialized (load or assign) directly in working memory. That is, the assign and load operations must be performed before a variable is implemented with the use and store operations.
- A variable allows only one thread to lock it at the same time, and lock and unlock must appear in pairs
- If you perform a lock operation on a variable, the value of the variable in the working memory will be emptied, and the value of the variable will need to be re-executed before the execution engine uses the variable, either the load or the assign operation.
- If a variable is not locked by the lock operation beforehand, it is not allowed to perform a unlock operation on it, nor is it allowed to unlock a variable that is locked by another thread.
- Before performing a unlock operation on a variable, you must first synchronize this variable into main memory (perform store and write operations).
3.3 re-ordering
In order to improve performance when executing programs, the compiler and processor often reorder instructions. Reordering is divided into three categories:
- The re-ordering of compiler optimizations. The compiler can rearrange the execution order of the statements without changing the semantics of the single-threaded procedure.
- Reordering of instruction-level parallelism. Modern processors use instruction-level parallelism 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.
- reordering of memory systems. Because the processor uses the cache and read-write buffers, this makes the load and storage operations appear to be executing in a disorderly order.
From the Java source code to the final actual execution of the sequence of instructions, the following three kinds of reordering:
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. The Java memory model divides the memory barrier into Loadload, Loadstore, Storeload, and Storestore four types:
3.4 Special rules for volatile variables
Keyword volatile can be said to be the most lightweight synchronization mechanism provided by a Java virtual machine! However, it is not easy to fully understand the correct and complete, so many programmers are accustomed to not use it, encountered the need to deal with multi-threaded data competition problems when using synchronized to synchronize.
When a variable is defined as volatile, it has two characteristics:
-
attribute one, guaranteeing the visibility of this variable to all threads
The" visibility "here means that when a thread modifies the value of the variable, The new value is immediately known to other threads. While ordinary variables do not do this, the value of the normal variable pass-through between threads needs to be done by main memory . If thread a modifies the value of an ordinary variable and then writes back to the main memory, and the other thread B reads the thread A after a write-back is completed, the value of the new variable is only visible to threads B. Although volatile has visibility, " operations based on volatile variables are safe in concurrency "The conclusion is not ! The volatile variable has no consistency problem in the working memory of each thread, but the , The operation that causes the volatile variable is not safe under concurrency!!  
-
Because volatile variables can only guarantee visibility (not guaranteed atomicity), in an operation scenario that does not conform to the following two rules, We still have to guarantee atomicity through locking (using atomic classes in synchronized or java.util.concurrent).
- The result of the operation does not depend on the current value of the variable, or can ensure that only a single thread modifies the value of the variable.
- Variables do not need to participate in invariant constraints with other state variables.
-
Feature two, prohibit command reordering optimization
A normal variable only guarantees that the correct result is obtained in all places where the result of the assignment is dependent on the execution of the method, and does not guarantee that the sequence of variable assignment operations is consistent with the order of execution in the program code. Because this is not perceptible during the execution of a thread's methods, the so-called "line range" described in the Java memory model is expressed as a serial semantics.
3.5 atomicity, visibility and ordering
The Java memory model is built around the 3 characteristics of how atomicity, visibility, and ordering are handled in the concurrency process , and let's take a look at what we have done to achieve these 3 features.
-
atomicity (atomicity)
monitor enter and monitor exit to use these two actions implicitly, These two bytecode directives are reflected in the Java code as the synchronization block--synchronized keyword , so the operation between synchronized blocks is also atomic.
-
visibility (Visibility)
visibility means when a thread modifies the value of a shared variable, Other threads can immediately be informed of this modification. We have discussed this in detail when explaining volatile variables. The Java memory model is , this that relies on main memory as a delivery medium to achieve visibility, whether it is a normal variable or a volatile variable, the difference between a normal variable and a volatile variable is , the special rules for volatile ensure that the new value can be sync to main memory immediately, and . Thus, it can be said that volatile guarantees the visibility of variables in multi-threaded operations, while ordinary variables do not guarantee this.
In addition to volatile, Java also has two keywords to achieve visibility, that is, synchronized and final. The visibility of a synchronization block is obtained by synchronizing this variable back into main memory (execute store, write operation) before performing a unlock operation on a variable, while the final keyword's visibility means that the final-modified field is initialized in the constructor once the initialization is complete. And the constructor does not pass the "this" reference (this refers to escaping is a very dangerous thing, other threads are likely to access the "initialized half" of the object through this reference), the value of the final field can be seen in other threads.
-
Order (ordering)
The ordering of the Java memory model is also discussed in detail in the previous explanation of volatile, and the natural ordering of Java programs can be summed up in one sentence: If you observe in this thread, all operations are orderly, and if you observe another thread in one thread, all operations are unordered. The first half of the sentence refers to "line range expression as a serial semantics" (Within-thread as-if-serial Semantics), the latter sentence refers to the "order reordering" phenomenon and "working memory and main memory synchronization delay" phenomenon.
The Java language provides the volatile and synchronized two keywords to ensure the ordering of operations between threads, and the volatile keyword itself contains the semantics of prohibiting command reordering, while synchronized is the " A variable that allows only one thread to lock on it at the same time. This rule determines that two synchronized blocks holding the same lock can only be entered serially .
3.6 Principle of antecedent occurrence
If all the ordering in the Java memory model is done only by volatile and synchronized, then some operations will become cumbersome, but we do not feel this when writing Java concurrency code because there is a "first occurrence" in the Java language (Happens-before) principle. This principle is very important, it is to determine whether the data is competitive, thread security is the main basis for this principle, we can through a few rules to solve the concurrency of the two operations between the possible conflicts between all problems.
The first occurrence is a partial-order relationship between two operations defined in the Java memory model, and if operation a precedes operation B, it is said that the effect of operation A can be observed by Operation B before Operation B, "Impact" includes modifying the values of shared variables in memory, sending messages, calling methods, and so on.
"Natural" pre-sex:
-
Order of Procedure Rules (Program order rule)
In a thread, in the order of the program code, the preceding operation precedes the written action. To be precise, you should control the flow order rather than the program code order, because you want to consider the structure of branching, looping, and so on.
-
Pipe lock Rules (Monitor lock rule)
A unlock operation first occurs after the lock operation that faces the same lock. The same lock must be emphasized here, and the "back" refers to the chronological order of the time.
-
Volatile variable rules (volatile Variable rule)
The write operation of a volatile variable precedes the reading of the variable, and the "back" in this case also refers to the order of time.
-
Thread initiation Rules (thread start rule)
The start () method of the thread object takes precedence over every action of this thread.
-
Thread termination rules (thread termination rule)
All operations in the thread occur first in the termination detection of this thread, and we can detect that the thread has terminated execution by means of the end of the Thread.Join () method, the return value of thread.isalive (), and so on.
-
Thread interrupt rules (thread interruption rule)
The invocation of the thread interrupt () method first occurs when the code of the interrupted thread detects that the interrupt event occurred, and can be detected by the thread.interrupted () method.
-
Object Finalization rule (Finalizer rule)
The initialization of an object (the end of the execution of the constructor) occurs first at the beginning of its finalize () method.
-
Transitivity (transitivity)
If the operation a first occurs in operation B, Operation B first occurs in Operation C, it can be concluded that the operation a precedes operation C.
Java memory model (JMM)