当前位置:网站首页>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
边栏推荐
- PCB design skills of EMC
- 快速搭建DMHS DM之间双向同步
- 华为高级工程师---BGP路由过滤及社团属性
- Matplotlib绘图笔记基础直线、折线、曲线
- Awk from introduction to earth (16) discussion on the types of awk variables -- about the two types of numbers and strings
- 03 | 项目部署:如何快速部署一个基于laravel框架开发的网站
- How to understand the adjective prefix of socket: "connection oriented" and "connectionless"
- mysql,我们如何得到受查询影响的行数?
- EMC rectification method set
- ASP. Net core technology insider and project practice after reading
猜你喜欢

Matplotlib绘图笔记基础直线、折线、曲线

DNA脱氧核糖核酸修饰金属铂纳米颗粒PtNPS-DNA|科研试剂

EMC rectification ideas

DNA-Ag2SQDs脱氧核糖核酸DNA修饰硫化银Ag2S量子点的合成方法

DNA modified noble metal nanoparticles | DNA deoxyribonucleic acid modified metal palladium Pd nanoparticles pdnps DNA

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

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

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

Oracle local network service

Introduction to magnetic ring selection and EMC rectification skills
随机推荐
Some experience of gd32 using Hal Library of ST and Gd official library
Lecture notes a utility for everyone to generate PCG
Clion debugging redis6 source code
2022/7/27 examination summary
Freezing and thawing of pytoch
Discrimination coverage index / index coverage / Samsung index
聊一聊数据库的行存与列存
Talk about row storage and column storage of database
After being accidentally dragged into QQ fraud group
XSS知识点和20字符短域名绕过
滴滴SQL面试题之打车业务问题如何分析
The core packages and middleware required for golang development cover all areas of the project and are worth collecting
华为高级工程师---BGP路由过滤及社团属性
Method of hiding scroll bar in wechat applet
Flowable workflow all business concepts
谈谈DOM0,DOM1,DOM2,DOM3
MySQL basic knowledge learning (II)
JUC原子类: CAS, Unsafe、CAS缺点、ABA问题如何解决详解
EMC rectification method set
【13】 Adder: how to build a circuit like Lego (Part 1)?