个人博客网:https://wushaopei.github.io/    (你想要这里多有)

一、安全发布对象-发布与逸出

1、发布与逸出定义

2、开发工作中涉及到的发布对象:

3、发布对象代码演示:

package com.mmall.concurrency.example.publish;

import com.mmall.concurrency.annoations.NoThreadSafe;
import lombok.extern.slf4j.Slf4j; import java.util.Arrays; /**
* @ClassName UnsafePublish
* @Description TODO
* @Author wushaopei
* @Date 2019/10/31 15:28
* @Version 1.0
*/
@Slf4j
@NoThreadSafe
public class UnsafePublish { private String [] states = {"a","b","c"}; public String [] getStates(){
return states;
} public static void main(String[] args) {
UnsafePublish unsafePublish = new UnsafePublish();
log.info("{}", Arrays.toString(unsafePublish.getStates())); //对私有属性数组进行修改
unsafePublish.getStates()[0] = "d";
log.info("{}",Arrays.toString(unsafePublish.getStates()));
}
}

Java并发编程 (五) 线程安全性-LMLPHP

执行结果:

15:31:56.516 [main] INFO com.mmall.concurrency.example.publish.UnsafePublish - [a, b, c]
15:31:56.521 [main] INFO com.mmall.concurrency.example.publish.UnsafePublish - [d, b, c] Process finished with exit code 0

Java并发编程 (五) 线程安全性-LMLPHP

分析:

通过public getStates方法发布了访问states的域,这样任何的外部线程都可以修改这个域,这样的发布对象其实是不安全的,因为无法假设其他线程会不会修改这个域,从而造成类里面这个状态的错误。

简单来说,这里通过new UnsafePublish()发布了这个类的实例,然后我们可以通过它提供给我们的public方法直接得到里面这个私有域states的引用,得到后我们就可以在其他的任何线程里面修改这个数组里面的值,这样一来,当我想要使用states里面的数据时,这时它里面的数据就是不完全确定的,因此,这样发布的对象就是线程不安全的。

4、对象逸出代码演示:

package com.mmall.concurrency.example.publish;

import com.mmall.concurrency.annoations.NoRecommend;
import com.mmall.concurrency.annoations.NoThreadSafe;
import com.sun.org.apache.bcel.internal.classfile.InnerClass;
import lombok.extern.slf4j.Slf4j; /**
* @ClassName Escape
* @Description TODO
* @Author wushaopei
* @Date 2019/10/31 15:39
* @Version 1.0
*/
@Slf4j
@NoThreadSafe
@NoRecommend
public class Escape { private int thisCanBeEscape = 0; public Escape(){
new InnerClass();
} private class InnerClass{
public InnerClass (){
log.info("{}",Escape.this.thisCanBeEscape);
}
} public static void main(String[] args) {
new Escape();
} }

Java并发编程 (五) 线程安全性-LMLPHP

执行结果:

15:41:32.697 [main] INFO com.mmall.concurrency.example.publish.Escape - 0

Process finished with exit code 0

Java并发编程 (五) 线程安全性-LMLPHP

分析:

可能导致this函数引用在构造过程中逸出的错误:

发布不确定对象会导致的错误:

注意:如果一个对象是可变对象,那么它就要安全发布才可以。

二、安全发布对象-四种方法-1

1、安全发布对象的四种方法:

2、使用代码演示安全发布对象的四种方法:

1) 线程不安全的单例-懒汉式

/*
* 懒汉模式
* 单例实例在第一次使用的时候进行创建
* */
@NoThreadSafe
public class SingletonExample1 { //私有构造函数
private SingletonExample1(){ } //单例对象
private static SingletonExample1 instance = null; //静态的工厂方法
public static SingletonExample1 getInstance(){
if (instance == null){
instance = new SingletonExample1();
}
return instance;
}
}

Java并发编程 (五) 线程安全性-LMLPHP

注意:懒汉模式是线程不安全的。

2) 饿汉式

/*
* 饿汉模式
* 单例实例在类装载的时候进行创建
* */
@ThreadSafe
public class SingletonExample2 { //私有构造函数
private SingletonExample2(){ } //单例对象
private static SingletonExample2 instance = new SingletonExample2(); //静态的工厂方法
public static SingletonExample2 getInstance(){
return instance;
}
}

Java并发编程 (五) 线程安全性-LMLPHP

饿汉模式是线程安全的,但是,如果私有构造方法中的操作太多,会造成加载时间过长;同时由于随着类装载,如果没有使用到该类的实例,会导致资源的浪费。

3)安全的懒汉式:

//静态的工厂方法
public static synchronized SingletonExample3 getInstance(){
if (instance == null){
instance = new SingletonExample3();
}
return instance;
}

Java并发编程 (五) 线程安全性-LMLPHP

注意:虽然这么添加同步锁后,线程安全了,但是会导致开销的增加,对性能有很大影响,不推荐这么操作。

4)使用synchronized对象锁修饰懒汉模式:

/*
* 懒汉模式 ->>双重同步锁单例
* 单例实例在第一次使用的时候进行创建
* */
@NoThreadSafe
public class SingletonExample4 { //私有构造函数
private SingletonExample4(){ } //单例对象
private static SingletonExample4 instance = null; //静态的工厂方法
public static SingletonExample4 getInstance(){
if (instance == null){ //双重检测机制
synchronized (SingletonExample4.class){ //同步锁
if(instance == null ){
instance = new SingletonExample4();
}
}
}
return instance;
}
}

Java并发编程 (五) 线程安全性-LMLPHP

问题:这里虽然使用了同步锁机制,但是依然是线程不安全的,为什么呢?

这里要从CPU的指令分析:

在完成以上三步后,instance就指向了实际分配内存的地址,也就是引用。在单线程情况下,执行CPU指令操作后,返回对象实例,是没有任何问题的。

但是,在多线程情况下,由于CPU存在指令重排序的问题,指令重排序对单线程是没有影响的,但是在多线程情况下就不一定了。

当JVM和CPU优化,发生了指令重排后,上面的执行顺序发生了变化:

如上,指令2和指令3发生了重排。

由重排序后的指令顺序可知,当线程执行到instance == null的判断时,此时由于指令3先执行了,那么instance就会认为当前的instance已经实例化过了,然后就会返回instance的实例;然而,此时的指令2并没有执行初始化对象,那么,一旦发生调用instance实例的操作,那么就会发生错误。

三、安全发布对象-四种方法-2

解决指令重排的问题:

1、使用volatile来修饰变量:

//单例对象 volatile + 双重检测机制 - 》 进制指令重排
private volatile static SingletonExample5 instance = null;

Java并发编程 (五) 线程安全性-LMLPHP

volatile可以制止CPU进行指令重排序的发生。

2、使用静态域、静态代码块实例化饿汉模式:

/*
* 饿汉模式
* 单例实例在类装载的时候进行创建
* */
@ThreadSafe
public class SingletonExample6 { //私有构造函数
private SingletonExample6(){ } //单例对象
private static SingletonExample6 instance = null; static {
instance = new SingletonExample6();
} //静态的工厂方法
public static SingletonExample6 getInstance(){
return instance;
} public static void main(String[] args) { System.out.println(getInstance().hashCode());
System.out.println(getInstance().hashCode());
System.out.println(getInstance().hashCode());
System.out.println(getInstance().hashCode()); }
}

Java并发编程 (五) 线程安全性-LMLPHP

执行结果:

1450495309
1450495309
1450495309
1450495309 Process finished with exit code 0

Java并发编程 (五) 线程安全性-LMLPHP

注意:当我们在写静态域以及静态代码块时一定要注意他们的顺序,顺序不同,执行的结果也会不同。

3、使用枚举实现一个线程安全的单例模式:

/**
* 枚举模式:最安全
* */
@ThreadSafe
@Recommend
public class SingletonExample7 { // 私有构造函数
private SingletonExample7() { } public static SingletonExample7 getInstance() {
return Singleton.INSTANCE.getInstance();
} private enum Singleton {
INSTANCE; private SingletonExample7 singleton; // JVM保证这个方法绝对只调用一次
Singleton() {
singleton = new SingletonExample7();
} public SingletonExample7 getInstance() {
return singleton;
}
}
}

Java并发编程 (五) 线程安全性-LMLPHP

枚举实现的单例比懒汉式线程要安全的多,同时,由于JVM的特性,在调用的时候才执行,也只执行一次,避免了重复执行造成的安全问题。避免了资源的浪费。

小结:

安全发布对象 - 发布、逸出

安全发布的四中方法 : 饿汉式、volatile、枚举

05-11 11:11