First, the key problem in concurrency and its solution
Key issues in Concurrency:
1. How threads communicate--how information is exchanged between threads
2. How threads are synchronized-control the relative execution order of threads
Two ways to solve the problem:
1. Implicit communication, display synchronization----the implicit communication between threads through a common state in shared memory, you must display the mutex that the specified thread sees to achieve synchronization
2. Explicit communication, implicit synchronization--there is no public state between the threads, communication through the explicit sending of messages, then because the message is sent before the message is received, you can implement implicit synchronization
Java chooses the way to share memory to solve two key problems in concurrency, so the communication between threads in Java is implicit and transparent to programmers, but requires programmers to control thread synchronization, such as using mutexes.
Second, JMM
JMM (Java memory model), which controls the communication between Java threads, defines the relationship between the thread-private local memory and the shared main memory, determining when a thread's write to a shared variable is visible to another thread.
For example, the communication of different Java threads must go through main memory, and JMM provides the programmer with memory visibility by controlling the interaction of main memory with the local memory of each thread.
Three, re-order
When compiling or executing, the compiler or processor will often reorder the instructions in the following three scenarios:
1. Compiler reordering: the Java compiler uses the semantics of Java code to reorder code directives based on optimization rules.
2. Reordering of machine instruction levels: Modern processors are smart enough to independently judge and change the order in which machine instructions are executed.
3. Reordering of memory systems: Due to buffering between the processor and the main memory, the loading and storage operations may be executed in a disorderly sequence.
Of these, 1 belongs to the compiler that specifies the rules by Java, and 2 and 3 are processor-level reordering. These reordering can cause some strange problems in the concurrency program, such as-visibility issues.
Now that the reordering is causing the problem, you can avoid these problems by preventing reordering at some point. The first is the compile-time prohibition of reordering, because the compile-time reordering rules are made by the Java compilation period, then Java certainly can do this prohibition. In the run-time, the processor-level prohibition of reordering requires the insertion of a specific type of memory barrier directive (barries/memory fence) to prohibit reordering. JMM is to ensure consistent memory visibility through the two-level prohibition reordering.
Java Concurrency Supplements (i)-concurrency, JMM, and reordering