- 饿汉式
/**
* 饿汉式,类加载的时候就会初始化
*
* 问题:
* 1. 通过反射可以破坏单例
* 2. 通过反序列化破坏单例
* 3. 通过Unsafe破坏单例,无法解决
*
* @author: optimjie
* @date: 2023-08-19 21:37
*/
public class Singleton1 {
private Singleton1() {
System.out.println("private Singleton1");
}
private static final Singleton1 INSTANCE = new Singleton1();
public static Singleton1 getInstance() {
return INSTANCE;
}
}
/**
* 饿汉式,解决上述问题
*
* @author: optimjie
* @date: 2023-08-19 21:44
*/
class Singleton2 {
private Singleton2() {
if (INSTANCE != null) { // 解决问题1
throw new RuntimeException("单例对象不能重复创建");
}
System.out.println("private Singleton1");
}
private static final Singleton2 INSTANCE = new Singleton2();
public static Singleton2 getInstance() {
return INSTANCE;
}
public Object readResolve() { // 解决问题2,反序列化时直接调用该方法
return INSTANCE;
}
}
- 懒汉式
/**
* 懒汉式
*
* 问题:
* 1. 线程安全问题
*
* @author: optimjie
* @date: 2023-08-19 21:55
*/
public class Singleton3 {
private Singleton3() {
System.out.println("private Singleton3");
}
private static Singleton3 INSTANCE = null;
public static Singleton3 getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton3();
}
return INSTANCE;
}
}
/**
* 懒汉式,解决上面问题
*
* 问题:
* 1. 每一次调用getInstance时都会加锁,但实际上只有一开始还没有创建Singleton4时才会有可能出现问题,
* 因此需要进一步优化
*
* @author: optimjie
* @date: 2023-08-19 22:07
*/
class Singleton4 {
private Singleton4() {
System.out.println("private Singleton3");
}
private static Singleton4 INSTANCE = null;
public static synchronized Singleton4 getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton4();
}
return INSTANCE;
}
}
/**
* 懒汉式,优化上面的问题,也称为双检锁优化,DCL
*
* @author: optimjie
* @date: 2023-08-19 22:09
*/
class Singleton5 {
private Singleton5() {
System.out.println("private Singleton3");
}
private static volatile Singleton5 INSTANCE = null; // 加volatile的原因,详情看volatile的那篇
public static Singleton5 getInstance() {
if (INSTANCE == null) {
synchronized (Singleton5.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton5();
}
}
}
return INSTANCE;
}
}
说明
===================================
仅作为校招时的《个人笔记》,详细内容请看【参考】部分
===================================
参考
- B站,黑马满老师