volatile
1.基本概念
volatile是JVM提供的轻量级的同步机制,他基本遵守了JMM的规范。volatile主要用来确保将变量的更新操作通知到其他线程。
- 当把变量用volatile修饰后,编译器不会对该变量进行指令重排序;
- volatile变量不会被缓存在寄存器或者对其他处理器不可见的地方,因此读取volatile类型的变量时总会返回最新写入的值;
- 在访问volatile变量时不会执行加锁操作,因此不会使执行线程阻塞。
2.三大特性
可见性
package com.example.juctest.volatileDemo;
import java.util.concurrent.TimeUnit;
/**
* @author Sonnie Guo
* @PackageName:com.example.juctest.volatileDemo
* @ClassName:VolatileTest
* @Description:
* @Date 2021/5/4 17:02
*/
@SuppressWarnings({"all"})
public class VolatileTest {
static volatile boolean flag = true;
public static void main(String[] args) {
visibility();
}
public static void visibility(){
new Thread(()->{
while(flag){}
System.out.println("AAA is ending!");
},"AAA").start();
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
flag = false;
},"BBB").start();
}
}
不保证原子性
package com.example.juctest.volatileDemo;
import java.util.concurrent.TimeUnit;
/**
* @author Sonnie Guo
* @PackageName:com.example.juctest.volatileDemo
* @ClassName:VolatileTest
* @Description:
* @Date 2021/5/4 17:02
*/
@SuppressWarnings({"all"})
public class VolatileTest {
public static void main(String[] args) {
atomic();
}
public static void atomic(){
MyData myData = new MyData();
for(int i = 0;i<20;i++){
new Thread(()->{
for (int j = 0;j < 1000;j++){
myData.add();
}
}).start();
}
while (Thread.activeCount()>2){
Thread.yield();
}
System.out.println(myData.getNum());
}
}
class MyData{
private volatile int num = 0;
public int add(){
return this.num++;
}
public int getNum(){
return this.num;
}
}
解读
num++ 的字节码指令
0 aload_0
1 dup
2 getfield #2 <com/Heygo/T1.n>
5 iconst_1
6 iadd
7 putfield #2 <com/Heygo/T1.n>
10 return
num++ 分为三步
- 第一步:执行 getfield 指令拿到主内存中 num 的值
- 第二步:执行 iadd 指令执行加 1 的操作(线程工作内存中的变量副本值加 1)
- 第三步:执行 putfield 指令将累加后的 num 值写回主内存
PS :iconst_1 是将常量 1 放入操作数栈中,准备执行 iadd 操作。
分析多线程写值,值丢失的原因
- 两个线程:线程 A和线程 B ,同时拿到主内存中 num 的值,并且都执行了加 1 的操作
- 线程 A 先执行 putfield 指令将副本的值写回主内存,线程 B 在线程 A 之后也将副本的值写回主内存
- 此时,可能就会出现写覆盖、写丢失的情况
那么如何解决原子性问题呢?
- 对 add() 方法加同步锁(加锁这个解决方法太重)
- 使用 Java.util.concurrent.AtomicInteger 类
package com.example.juctest.volatileDemo;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author Sonnie Guo
* @PackageName:com.example.juctest.volatileDemo
* @ClassName:VolatileTest
* @Description:
* @Date 2021/5/4 17:02
*/
@SuppressWarnings({"all"})
public class VolatileTest {
public static void main(String[] args) {
atomic();
}
public static void atomic(){
MyData myData = new MyData();
for(int i = 0;i<20;i++){
new Thread(()->{
for (int j = 0;j < 1000;j++){
myData.add();
}
}).start();
}
while (Thread.activeCount()>2){
Thread.yield();
}
System.out.println(myData.getNum());
}
}
//使用concurrent包下的AtomicInteger类
@SuppressWarnings({"all"})
class MyData{
private AtomicInteger num = new AtomicInteger();
public int add(){
return this.num.getAndIncrement();
}
public AtomicInteger add(int i){
this.num.getAndAdd(i);
return this.num;
}
public AtomicInteger getNum(){
return this.num;
}
}
//加同步锁的方式
// @SuppressWarnings({"all"})
//class MyData{
// private volatile int num = 0;
// public synchronized int add(){
// return this.num++;
// }
// public synchronized int add(int i){
// num += i;
// return this.num;
// }
// public int getNum(){
// return this.num;
// }
//}
有序性
3.DCL单例模式
DCL,Double Check Lock即双端检索机制,在加锁前后进行判断。
由于指令重排的存在,DCL(双端检索机制)不一定线程安全,实例化instance分为三步:
- 1.分配对象内存空间
- 2.初始化对象
- 3.指向刚分配的内存地址,此时instance!=null
其中,第二三步不存在数据依赖关系,因此当一条线程访问instance不为null时,由于instance实例未必已初始化完成,从而造成了线程安全问题。
package com.example.juctest.volatileDemo;
/**
* @author Sonnie Guo
* @PackageName:com.example.juctest.volatileDemo
* @ClassName:DCLDemo
* @Description:
* @Date 2021/5/4 20:41
*/@SuppressWarnings({"all"})
public class DCLDemo {
public static void main(String[] args) {
for (int i = 0;i < 1000;i++){
new Thread(()->{
Singleton.getInstance();
},String.valueOf(i)).start();
}
}
}
@SuppressWarnings({"all"})
class Singleton{
private static instance singleton = null;
private Singleton(){
System.out.println("调用构造器");
}
public static Singleton getInstance(){
if(instance==null){
synchronized (Singleton.class){
if (instance==null){
instance = new Singleton();
}
}
}
return instance;
}
}
**因此,正确做法应该要加上volatile,禁止指令重排。**完整代码如下:
package com.example.juctest.volatileDemo;
/**
* @author Sonnie Guo
* @PackageName:com.example.juctest.volatileDemo
* @ClassName:DCLDemo
* @Description:
* @Date 2021/5/4 20:41
*/@SuppressWarnings({"all"})
public class DCLDemo {
public static void main(String[] args) {
for (int i = 0;i < 1000;i++){
new Thread(()->{
Singleton.getInstance();
},String.valueOf(i)).start();
}
}
}
@SuppressWarnings({"all"})
class Singleton{
private volatile static Singleton instance = null;
private Singleton(){
System.out.println("调用构造器");
}
public static Singleton getInstance(){
if(instance==null){
synchronized (Singleton.class){
if (instance==null){
instance = new Singleton();
}
}
}
return instance;
}
}