Just looked at the difference between synchronized and volatile, take notes here.
How is memory allocated in multi-threading?
Divided into primary memory and thread memory, when a thread shares a variable with another thread, it copies the variables of the main memory to the thread memory. When a change occurs to a variable, it is synchronized to the main memory, and the main memory is synchronized to the other thread memory.
Synchronized Achieving visibility
JMM to synchronized regulations:
Line Cheng, the value of the shared variable in the thread memory is emptied to re-read the new value from main memory when the shared variable is used.
Before line threads unlocked, you must flush the current value of the shared variable to main memory.
The thread executes the mutex code procedure:
1. Get the mutex lock
2. empty thread memory
3. Copy the latest copy from main memory to thread memory
4. Execute code
5. flush the changed variable to main memory
6, release the mutex lock
Instruction reordering: The order in which the code is written differs from the order in which it is actually executed to improve the performance of the program.
Compiler refinement reordering: Compiler reordering
instruction-level parallel optimizations from sort: CPU Parallel Execution Optimization
Memory system from Sort: optimization of read-write cache
As-if-serial: Regardless of the reordering, the results of the program execution should be consistent with the results of the code order execution.
The Java compiler guarantees as-if-serial, but does not guarantee sequential execution in multithreaded programs.
Volatile for visibility
by Adding a memory barrier and no reordering optimizations, the store barrier command is added after the volatile write operation , and the Load Barrier command is added before the read Operation .
Volatile does not guarantee the atomicity of variable operations
Lock for visibility
Lock lock = new Reentrantlock ();
Lock.lock ();
try{
}finally{
Lock.unlock ();
}
Memory visibility in Java Multi-threading