CPU memory models and memory models to explain JAVA

CPU memory model

Before explaining JAVA memory model, memory model to understand the CPU, memory model because JAVA is saying it is very similar.

CPU memory model
Core is the figure of a CPU. You can see:

  1. L1 and L2 are each CPU own cache
  2. L3 cache is shared among a plurality of CPU.
  3. Yellow is the main memory.
  4. L1, L2, L3, stored speed, gradually decreases and storing things.
  5. L1 and L2 cache hit rate is 80 percent for
  6. L3 cache accounting data reaches about 4%.

JAVA memory model

Here Insert Picture Description
This can be seen with the CPU memory is very similar. Memory corresponding to the yellow portion of the L3 cache of the CPU. But you can also see ah, Copy Memory is copied in. It is because of the existence of this thing, leads to variable visibility problems.

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.

happen-before rules:

Here Insert Picture Description

Guess you like

Origin juejin.im/post/5e84c15851882573bb78e9fa