Visibility: A thread changes the value of a shared variable to be seen by other threads in time.
Shared variables : If a variable has a copy in the memory of multiple threads, then this variable is a shared variable for these threads.
Java memory model (JMM)
Describes the access rules for various variables (thread-shared variables) in Java programs, and the underlying details of storing variables in the JVM in memory and in-memory read-out variables.
1) All variables are stored in main memory
2) Each thread has its own independent working memory, which holds a copy of the variable used in the thread (a copy of the variable in main memory).
Article Two provisions
1) All operations of a thread on a shared variable must be made in its own working memory and cannot be read and written directly from main memory
2) variables in the working memory of other threads cannot be accessed between different threads, and the transfer of variable values between threads needs to be done through main memory.
The principle of shared variable visibility implementation
Thread 1 modification of shared variables to think of thread 2 in time, you must go through the following 2 steps:
1) Flush memory variables updated in working memory 1 to main memory.
2) Update the value of the smallest shared variable in main memory to work memory 2.
How visibility is implemented the visibility implementation of Java language level support:
1) Synchronized
2) volatile
Synchronized achieving visibility
Synchronized can achieve:
1) atomicity (synchronous)
2) Visibility
JMM two provisions on synchronized:
1) Before line threads unlocked, you must flush the current value of the shared variable to main memory.
2) When the line Cheng, the value of the shared variable in the working memory is emptied, so the minimum value needs to be re-read from the main memory when using shared variables (note: The same lock is required to add and unlock)
The process by which threads execute mutually exclusive code:
1) Obtain the mutex lock
2) Empty working memory
3) Copy the latest copy of the variable from the main memory to the working memory
4) Code Execution
5) Flush the value of the changed shared variable to main memory
6) Release the mutex.
Re-order
Reorder: The order in which code is written differs from the order in which it is actually executed, which is an optimization of the compiler or processor to improve threading performance.
1) Compiler-optimized reordering (compiler Optimizations)
2) Instruction-level parallel reordering (processor optimization)
3) Re-sequencing of the memory system (processor optimization)
As-if-serial
As-if-serial: Regardless of reordering, the results of the program execution should be consistent with the results of the Code order execution (Java compiler, runtime, and processor will ensure that Java follows the as-if-serial semantics on a single thread).
Java thread-java Multi-thread visibility