JMM

126 阅读1分钟

CPU架构缓存一致性

缓存一致性.png

缓存一致性协议

缓存一致性协议给缓存行(通常为64字节)定义了个状态,用来描述该缓存行是否被多处理器共享、是否修改,缓存一致性协议最出名的是mesi

独占(exclusive) 共享(share) 修改(modified) 失效(invalid)

CPU相关术语

内存屏障:是一组处理器指令,用于实现对内存操作的顺序执行

缓存行:缓存中可以分配的最小存储单位

原子性

相关操作不会被中途其他线程干扰,一般通过同步机制实现

可见性

是一个线程修改了某个共享变量,其状态能够立即被其他线程知晓,通常被解释为将线程本地状态反映到主内存上,volatile就是负责保证可见性的

有序性

是保证线程内串行语义,避免指令重排等

JMM内存分析

image-20210901150142146.png

private static volatile boolean initialization = false;

public static void main(String[] args) throws InterruptedException {
    new Thread(()->{
        System.out.println("thread one start...");
        while (!initialization) {
        }
        System.out.println("thread one stop...");
    }).start();

    Thread.sleep(1000);

    new Thread(()->{
        System.out.println("thread two start...");
        init();
        System.out.println("thread two stop...");
    }).start();
}

public static void init() {
    initialization = true;
    System.out.println("初始化成功");
}

image-20210901150324988.png

内存屏障

1、阻止屏障两侧的指令重排序; 2、强制把写缓冲区/高速缓存中的脏数据等写回主内存,让缓存中相应 的数据失效。

happen-before规则

  1. 单线程的每个操作,happen-before于该线程中任意后序操作
  2. volatile写happen-before与后续对这个变量的读
  3. synchronized解锁happen-before后续对这个锁的加锁
  4. final变量的写happen-before于final域对象的读,happen-before后续对final变量的读
  5. 传递性