CPU memory model
Before explaining JAVA memory model, memory model to understand the CPU, memory model because JAVA is saying it is very similar.
- L1 and L2 are each CPU own cache
- L3 cache is shared among a plurality of CPU.
- Yellow is the main memory.
- L1, L2, L3, stored speed, gradually decreases and storing things.
- L1 and L2 cache hit rate is 80 percent for
- L3 cache accounting data reaches about 4%.
JAVA memory model
Visibility problems
class XXX {
private static int a = 0;
Thread threadA = new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " a = " + a);
a = 1;
System.out.println(Thread.currentThread().getName() + " a = " + a);
}, "ThreadA");
Thread threadB = new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " a = " + a);
a = 1;
System.out.println(Thread.currentThread().getName() + " a = " + a);
}, "ThreadB");
}
复制代码
When the new multiple threads to modify a variable, visibility problems arise. That is: thread-A: a -> 1. However, thread-B is not necessarily a one to read, or may be 0;
Reordering problem
Simple explanation:
java during program execution, instructions may be rearranged. A code sequence is:
b = 1;
x = a;
复制代码
But it may become the implementation of:
x = a;
b = 1;
复制代码
Source code into real generally performed after: source -> Compiler discouraged sorted -> processor reordering -> the final order of execution
but! ! ! Reordering is not unconditionally to reordering. He must follow a happen-before rule.