当前位置:网站首页>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
边栏推荐
- How to analyze the taxi business problem of didi SQL interview question
- The underlying principles of RDB persistence and AOF persistence of redis
- DNA modified noble metal nanoparticles | DNA modified copper nanoparticles cunps-dna | research points
- 基于单例模式的yaml参数配置
- Huawei Senior Engineer -- BGP routing filtering and community attributes
- DNA修饰金属铑Rh纳米颗粒RhNPS-DNA(DNA修饰贵金属纳米颗粒)
- How to understand the adjective prefix of socket: "connection oriented" and "connectionless"
- “蔚来杯“2022牛客暑期多校训练营2补题记录(DGHJKL)
- Industry standards and certification of common electronic products
- awk从入门到入土(16)awk变量类型探讨--关于数字和string两种类型
猜你喜欢

Delete the nodes in the linked list - daily question

EMC rectification method set

Dry goods | share an EMC actual case and rectification process

快速搭建DMHS DM之间双向同步

Introduction to magnetic ring selection and EMC rectification skills

记录一次mycat连接Communications link failure问题解决

Information system project manager must recite the core examination site (41) risk management plan

Clion debugging redis6 source code

Copper indium sulfide CuInSe2 quantum dots modified DNA (deoxyribonucleic acid) DNA cuinse2qds (Qiyue)

EMC设计攻略 —时钟
随机推荐
Introduction to magnetic ring selection and EMC rectification skills
[300 + selected interview questions from big companies continued to share] big data operation and maintenance sharp knife interview question column (VIII)
2022/7/27 examination summary
mysql:LIKE和REGEXP操作有什么区别?
Dry goods | share an EMC actual case and rectification process
Opentsdb time series database
How to close the blocked program process?
DNA modified rhodium RH nanoparticles rhnps DNA (DNA modified noble metal nanoparticles)
【花书笔记】 之 Chapter01 引言
How to analyze the taxi business problem of didi SQL interview question
03 | project deployment: how to quickly deploy a website developed based on the laravel framework
win系统添加打印机
谈谈DOM0,DOM1,DOM2,DOM3
【13】加法器:如何像搭乐高一样搭电路(上)?
After being accidentally dragged into QQ fraud group
DNA-Ag2SQDs脱氧核糖核酸DNA修饰硫化银Ag2S量子点的合成方法
ArcGIS JS customizes the accessor and uses the watchutils related method to view the attribute
EMC rectification method set
Mysql, how can we get the number of rows affected by the query?
XMPP Service Research (II) prosody create account