当前位置:网站首页>Volatile:JVM 我警告你,我的人你别乱动
Volatile:JVM 我警告你,我的人你别乱动
2022-08-09 15:17:00 【InfoQ】
- 禁止指令重排
- 保证内存可见
指令重排序
public class Singleton { private static volatile Singleton instance = null; private Singleton() { } public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; }}
instance = new Singleton();
- 分配一块内存空间
- 初始化
- 返回内存地址
Object o = new Object();

- new 用来分配一块内存空间
- invokspecial 调用了 Object 的 init() 方法,做了初始化
- astore_1 就是将 o 指向了 Object 实例对象的内存地址,完成赋值
private static int x = 0;private static int y = 0;private static int a = 0;private static int b = 0;public static void main(String[] args) throws InterruptedException { int i = 0; while (true) { i++; x = 0; y = 0; a = 0; b = 0; Thread one = new Thread(() -> { a = 1; x = b; }); Thread two = new Thread(() -> { b = 1; y = a; }); one.start(); two.start(); one.join(); two.join(); if(x == 0 && y == 0) { log.info("第 {} 次,x = {}, y = {}", i, x, y); break; } }}



内存可见性
private static boolean flag = true;private static void justRun() { System.out.println("Thread One Start"); while (flag) {} System.out.println("Thread One End");}public static void main(String[] args) throws InterruptedException { new Thread(() -> justRun(), "Thread One").start(); TimeUnit.SECONDS.sleep(1); flag = false;}
private static volatile boolean flag = true;


总结
边栏推荐
猜你喜欢
网络——数据交换方式
Chapter 2: Creating Interactive Maps (2.4-2.6)
C语言循环结构之万恶之源goto语句
易基因|作物育种:DNA甲基化在大豆优良品种培育中的作用研究成果
Heap series_0x0A: 3 methods to solve the heap overflow problem at once
巧用Prometheus来扩展kubernetes调度器
三.两数交换 空指针 && 野指针 解引用问题
ESP8266-Arduino编程实例-MQ-5液化天然气传感器驱动
继承关系下构造方法的访问特点
2022年8月9日:用C#生成.NET应用程序--使用 Visual Studio Code 调试器,以交互方式调试 .NET 应用(不会,失败)
随机推荐
ESP8266-Arduino编程实例-MQ-5液化天然气传感器驱动
一.字符 字符串 指针字符
学习编程的第三天
继承和选择器的权重
2022年华数杯C题插层熔喷完整解题思路(附代码+详细讲解视频)
第三章:GEE数据的使用(3.4-3.11)
The web project accesses static resources inside the jar
3. Using Earth Engine Data
【Chinese and English Catalog】Introduction
map和set容器
初识C语言(1)
C语言三大循环while,for,do...while
良匠-手把手教你写NFT抢购软(三)
低代码的开发前景
Foreword: About the author Dr. Wu Qiusheng and an introduction to the book
小心使用C语言realloc()函数!!!
Chapter 3: Use of GEE Data (3.4-3.11)
网络——IPV4地址(二)
选择器的使用
网络——数字数据编码