当前位置:网站首页>DCL singleton mode
DCL singleton mode
2022-07-28 08:03:00 【The galloping snail has been occupied】
The main function of singleton mode is , In the case of multithreading, only a single object can be obtained , So as to avoid all kinds of problems caused by this ;
Singleton mode 3 Chinese writing
Catalog
1. Add... Directly to the method synchronized
private static Single instance;
public static synchronized Single getInstance(){
if(instance == null){
instance = new Single();
}
return instance;
}
The disadvantage of this method is , Every time you execute this code, you need to acquire the lock , This will affect efficiency to a certain extent ;
2.DCL( Double detection and locking )
public class Single{
private volatile static Single instance;
private Single(){
}
public static Single getInstance(){
if(instance == null ){
synchronized(Single.class){
if(instance == null){
instance = new Single();
}
}
}
return instance;
}
}
DCL Compared with the simple and crude direct locking above , There is an advantage , You don't have to lock every time you get an instance ; Efficiency will improve a little when concurrency is high ;
Explain it. , Why do it 2 Time of null Judge ?
Just imagine , Such a scene : Suppose there are now 5 Threads execute this code at the same time , At the same time instance == null;
They will compete for locks , But in the end, only one thread will get the lock , That is to say, there are 4 Threads got stuck here without locks , Wait for the thread that obtains the lock to finish executing this code , Remaining after releasing the lock 4 Threads continue to compete ;
The first thread to obtain the lock gets the execution right of this code , It will definitely be completed instance Instance initialization ; And then there's 4 If a thread does not do it at this time null Judgment will continue to give instance Give a new life Model object , As a result, the subsequent thread and the previous thread do not obtain an instance object , To make a mistake ;
This is why we need double detection ;
There is actually another problem , That is why we should add volatile; What's the problem if you don't add it ?
private volatile Single instance;
volatile What is the function of keywords ?
《 In depth understanding of java Virtual machine version 2 》( Zhi-ming zhou ) The explanation of
By volatile Decorated variables have two characteristics :
1. Ensure the visibility of this variable to all threads , Visibility here means that the update of this variable modified by the current thread is immediately visible to other threads , But not thread safe ;
2,volatile The second semantics of is to prohibit instruction reordering optimization , Ordinary variables only ensure that all results are correct during the execution of the method , However, it is not guaranteed that the order of variable assignment operation is consistent with the execution order in the code
stay Java Instantiation is not an atomic operation. In fact, there are probably the following steps :
Class loading , Allocate object space , Initialize object variables , Assign values to the variables of the object , Return the object address to the variable
Not used volatile Keyword code may not complete object instantiation , Returning the address of this instance may cause some unexpected errors ; Therefore, you must add volatile keyword ;( Of course, I have done several experiments without this volatile, I didn't make any mistakes , It may be that errors are occasionally reported under high concurrency )
3. Use DCL The hidden danger of
The singleton pattern created using the above method will be destroyed by reflection , Using reflection to get the construction method, you can create an instance , The code is as follows :
Class<Single> dclClass = Single.class;
Constructor<Single> declaredConstructor = dclClass.getDeclaredConstructor();
declaredConstructor.setAccessible(true);
Single refSingle =declaredConstructor.newInstance();
Use variables in the construction method to judge , If instance != null Just report a mistake ; That's not going to work ; It can also be modified by reflection instance Value ;
private Single(){
if(instance != null)throw new RuntimeException(" don't use reflect create object");
}
Attack code :
Class<Single> dclClass = Single.class;
Field instance = dclClass.getDeclaredField("instance");
instance.setAccessible(true);
instance.set(null,null);
Constructor<Single> declaredConstructor = dclClass.getDeclaredConstructor();
declaredConstructor.setAccessible(true);
Single refSingle =declaredConstructor.newInstance();
How to defend against creating instance objects through reflection mechanism ?
1. Create static inner classes
public class HungryMan {
private HungryMan() {
if(InnerSingle.single != null){
throw new RuntimeException(" don't use reflect create object");
}
}
public static HungryMan getInstance(){
return InnerSingle.single;
}
private static class InnerSingle{
private static final HungryMan single = new HungryMan();
}
}
Reflection cannot be modified InnerSingle.single Value , Because being final Modify the , It will not change after initialization ; If you modify through reflection, you will also report an error ;
2. Create enumeration class
public class SingleTest{
public static Single getInstance(){
return Single.single;
}
}
public enum Single{
single
}
Take advantage of enumeration class features , Each instance will only be loaded once, which is naturally suitable for single instances ;
Why? enum Class will only be loaded once. See :enum Detailed explanation
边栏推荐
- Understanding of spark operator aggregatebykey
- Which of class A and class B is more stringent in EMC?
- DNA modified noble metal nanoparticles | DNA modified copper nanoparticles cunps-dna | research points
- Solve the inherent defects of CNN! Common CNN architecture ccnn is coming | icml2022
- Collector原理解析
- "Wei Lai Cup" 2022 Niuke summer multi school training camp 2 supplementary question record (dghjkl)
- Discrimination coverage index / index coverage / Samsung index
- DNA modified noble metal nanoparticles | DNA deoxyribonucleic acid modified metal palladium Pd nanoparticles pdnps DNA
- What if the computer folder cannot be renamed?
- Basic dictionary of deep learning --- activation function, batch size, normalization
猜你喜欢

win系统添加打印机

Delete the nodes in the linked list - daily question

谈谈DOM0,DOM1,DOM2,DOM3

数据化管理洞悉零售及电子商务运营——数据化管理介绍
![[Google] solve the problem that Google browser does not pop up the account and password save box and cannot save login information](/img/b3/2592e941f5d8f3505fb9763e8947a6.png)
[Google] solve the problem that Google browser does not pop up the account and password save box and cannot save login information

03 | project deployment: how to quickly deploy a website developed based on the laravel framework

演讲笔记 适合所有人的实用程序生成 PCG

@The role of documented

YOLO系列损失函数详解

使用FFmpeg来批量生成单图+单音频的一图流视频
随机推荐
Synthesis of dna-ag2sqds DNA modified silver sulfide Ag2S quantum dots
The penultimate node in the linked list - Double finger
[dry goods] 32 EMC standard circuits are shared!
Method of hiding scroll bar in wechat applet
【青鸟学员故事】追风少年“李晓亮”
Basic dictionary of deep learning --- activation function, batch size, normalization
EMC rectification method set
2022/7/27 examination summary
Using identity framework to realize JWT identity authentication and authorization in.Net 6.0
机械革命蛟龙p有线网卡驱动打不上
Redis of non relational database [jedis client +jedis connection cluster]
0727~ sorting out interview questions
How do we run batch mode in MySQL?
OpenTSDB-时序数据库
Mysql, how many columns can be used to create an index?
我们如何在mysql中运行批处理模式?
js卡片层叠样式的图片切换js特效
DNA修饰金属铑Rh纳米颗粒RhNPS-DNA(DNA修饰贵金属纳米颗粒)
辨析覆盖索引/索引覆盖/三星索引
@The role of documented