当前位置:网站首页>单例模式-五种方式 不要被克隆
单例模式-五种方式 不要被克隆
2022-08-09 14:55:00 【按劳分配】
单例模式-五种方式 不要被克隆
单例模式需要考虑,线程安全问题,效率问题,防止反射和防止被反序列化。
单例模式-防止反射和反序列化:
private Single1() {
if (null != instance) {
throw new RuntimeException();
}
}
//在反序列化的时候直接返回单例
private Object readResolve() throws ObjectStreamException {
return instance;
}
1、饿汉模式
private static Single1 instance = new Single1();
优点:不存在线程安全问题,不存在同步sync性能问题。
缺点:由于在声明的时候已经初始化,即使该类没有使用也会占用内存。
2、懒汉模式
public static Single2 instance;
private Single2(){
}
public synchronized Single2 getInstance(){
if(null==instance){
instance = new Single2();
}
return instance;
}
优点:使用时候创建,可能节约内存。
缺点:每次都要锁住方法,即使instance已经被初始化,导致效率较低。
3、Double CheckLock DCL模式
public class Single3 {
private static Single3 instance;
private Single3() {
}
public static Single3 getInstance() {
if (null == instance) {
synchronized (Single3.class) {
instance = new Single3();
}
}
return instance;
}
}
优点:不会一直锁住,效率高些,在使用的时候才会初始化,也避免了内存浪费。
缺点:DCL失效,由于instance = new Single3();虽然是一条语句,但是却不是原子操作。实例化对象的汇编指令大致有三件事
1、给instance分配内存
2、调用new Single3()初始化函数
3、将分配的内存空间地址赋值给instance
在jdk1.5之前执行顺序可能是1-2-3,或者1-3-2,如果是1-3-2,可能比得线程拿到的就是一个内存地址而instance没有调用初始化方法new Single3(),
jdk1.5之后修复,加入关键字volatile,避免以上错误,所以确保DCL正确性,给变量加上这个属性
public class Single3 {
private volatile static Single3 instance;
private Single3() {
}
public static Single3 getInstance() {
if (null == instance) {
synchronized (Single3.class) {
instance = new Single3();
}
}
return instance;
}
}
4、静态内部类
public class Single4 {
private Single4(){
}
public static Single4 getInstance(){
return SingleHolder.instance;
}
private static class SingleHolder{
private static final Single4 instance = new Single4();
}
}
在加载类Single4的时候,不会初始化instance。调用getInstance()才会加载SingleHolder类,避免线程安全,没有内存不必要浪费,不用锁。推荐使用。
5、枚举单例
由于枚举本来就是实例数量已知且固定的,所以如果枚举类只有一个实例,也就实现了单例,而且不用考虑被反射和反序列化 而被克隆,任何情况下
都是单例的。
public enum Single5 {
Instance;
private Single5() {
init();
}
public void init() {
}
}
边栏推荐
猜你喜欢
随机推荐
Example of file operations - downloading and merging streaming video files
Several important functions of singly linked list (including insertion, deletion, reversal, etc.)
How to make your quantitative trading system have probabilistic advantages and positive return expectations?
ImageWatch无法显示图像
浏览器中的302你真的知道吗
Mathematica 数据分析(简明)
A shortcut method for writing menu commands in C
LNK1123: Failed during transition to COFF: invalid or corrupt file
.Net Core 技巧小结
Mathematica 作图详解
常见的数学物理方程
.Net Core后台任务启停(BackgroundService)
Noun concept summary (not regularly updated ~ ~)
NetCore 5.0连接MySql
SNR 信噪比
What are the misunderstandings about the programmatic trading system interface?
Welcome to use CSDN - markdown editor
C language operator precedence
Simply record offsetof and container_of
pyspark jieba 集群模型 对文本进行切词