当前位置:网站首页>Implementation of six singleton modes
Implementation of six singleton modes
2022-07-02 11:06:00 【LHT-2787】
One 、 Definition of singleton pattern
Definition : Ensure that a class has only one instance , And provide the global access point of the instance .
The advantage of this is : Some examples , Only one is enough for the overall situation , Using singleton mode can avoid a globally used class , Frequent creation and destruction , Consume system resources .
Two 、 Design elements of singleton pattern
A private constructor ( Make sure that only singleton classes can create instances themselves )
A private static variable ( Make sure there is only one instance )
A public static function ( Provide the calling method to the user )
In a nutshell , The construction method of singleton class does not allow others to modify and use ; And the singleton class creates only one instance itself , The instance , Others cannot modify and directly use ; Then the singleton class provides a calling method , I want to use this example , Can only call . This ensures that the global only creates an instance once .
3、 ... and 、 Singleton mode 6 Implementation and advantages and disadvantages of each implementation
( One ) Slacker type ( Thread unsafe )
Realization :
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {
}
public static Singleton getUniqueInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
explain : Don't create an instance first , When called for the first time , Create an instance , So it's called lazy .
advantage : Delayed instantiation , If you don't need to use this class , Will not be instantiated , Save system resources .
shortcoming : Thread unsafe , Multi-threaded environment , If multiple threads enter at the same time if (uniqueInstance == null) , If not instantiated at this time , That is to say uniqueInstance == null, Then there will be multiple threads executing uniqueInstance = new Singleton(); , Multiple instances will be instantiated ;
( Two ) Hungry Chinese style ( Thread safety )
Realization :
public class Singleton {
private static Singleton uniqueInstance = new Singleton();
private Singleton() {
}
public static Singleton getUniqueInstance() {
return uniqueInstance;
}
}
explain : Whether you need to use this instance or not , Directly instantiate a good instance first ( Like a starving ghost , So it's called hungry Han style ), Then when it needs to be used , The direct adjustment method can be used .
advantage : Instantiate an instance in advance , Avoid thread unsafe problems .
shortcoming : Directly instantiate the instance , No longer delay instantiation ; If the system does not use this instance , Or you need to use this instance after the system runs for a long time , Will waste the resources of the operating system .
( 3、 ... and ) Slacker type ( Thread safety )
Realization :
public class Singleton {
private static Singleton uniqueInstance;
private static singleton() {
}
private static synchronized Singleton getUinqueInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
explain : The implementation and Thread unsafe lazy Almost the same as , The only difference is , stay get On the way Added one lock . In this way , Multiple threads access , Each time, only the thread that gets the lock can enter the method , Avoid the unsafe problem of multithreading .
advantage : Delay instantiation , Save resources , And it's thread safe .
shortcoming : Although it solves the problem of thread safety , But the performance is reduced . because , Even if the instance has been instantiated , There will be no thread safety problems in the future , But the lock is still there , Each time, only the thread that gets the lock can enter this side *** Block threads , Waiting time is too long .
( Four ) Double check lock implementation ( Thread safety )
Realization :
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton() {
}
public static Singleton getUniqueInstance() {
if (uniqueInstance == null) {
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
explain : The number of double checks is equivalent, so it has been improved Thread-safe loafers . Thread-safe loafers The disadvantage is that the performance is reduced , The reason is that even if the instance has been instantiated , There's still a lock every time . And now , We changed the position of the lock , And added an extra check . That is to say , First judge whether the instance already exists , If it already exists , The locked method in the judgment method will not be executed . And if the , Before instantiation , Multiple threads went in , Nothing , Because the method inside has a lock , Only one thread will enter the innermost method and instantiate the instance . In this way , At most , That is, when it is instantiated for the first time , There will be thread blocking , Then there will be no thread blocking problem .
Why use volatile The keyword is decorated uniqueInstance Instance variables ?
uniqueInstance = new Singleton(); This code is executed in three steps :
by uniqueInstance Allocate memory space
initialization uniqueInstance
take uniqueInstance Point to the allocated memory address
The normal order of execution is of course 1>2>3 , But because of JVM Has the characteristic of instruction rearrangement , The order of execution may become 1>3>2.
In a single threaded environment , There is no problem with instruction rearrangement ; In a multithreaded environment , As a result, some threads may get uninitialized instances .
for example : Threads A Only execution 1 and 3 , The thread B To call getUniqueInstance(), Find out uniqueInstance Not empty , Then get it uniqueInstance example , But in fact, at this time uniqueInstance It's not initialized yet .
The solution is to add volatile Keyword modification uniqueInstance ,volatile It will be banned JVM The command rearrangement of , It can ensure the safe operation in multi-threaded environment .
advantage : Delay instantiation , Save resources ; Thread safety ; And relative to Thread-safe loafers , Performance improved .
shortcoming : volatile keyword , It also has some impact on performance .
( 5、 ... and ) Static inner class implementation ( Thread safety )
Realization :
public class Singleton {
private Singleton() {
}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getUniqueInstance() {
return SingletonHolder.INSTANCE;
}
}
explain : First , When the outer class Singleton When loaded , Static inner class SingletonHolder Not loaded into memory . When calling getUniqueInstance() When the method is used , Will run return SingletonHolder.INSTANCE; , Triggered SingletonHolder.INSTANCE , At this point, the static inner class SingletonHolder Will be loaded into memory , And initialize INSTANCE example , and JVM Will make sure that INSTANCE Instantiated only once .
advantage : Delay instantiation , Save resources ; And thread safety ; Performance also improved .
( 6、 ... and ) Enumeration class implementation ( Thread safety )
Realization :
public enum Singleton {
INSTANCE;
// Add the actions you need
public void doSomeThing() {
}
}
explain : The creation of default enumeration instances is thread safe , And in any case, it is a single case .
advantage : Written in simple , Thread safety , Naturally prevents reflection and deserialization calls .
Prevent deserialization
serialize : hold java Object to byte sequence ;
Deserialization : Create a new byte in memory through these byte sequences java Object procedure ;
explain : Deserialization Write a single instance object to disk and read it back , Thus a new example is obtained .
We want to prevent deserialization , Avoid getting multiple instances .
Enumeration classes naturally prevent deserialization .
Other single mode Can pass rewrite readResolve() Method , To prevent deserialization , Make the instance unique readResolve() :
1
2
3
private Object readResolve() throws ObjectStreamException{
return singleton;
}
Four 、 Application scenario of singleton mode
Examples of application scenarios :
Website counter .
Application log application .
Web Reading of configuration objects in the project .
Database connection pool .
Multithreaded pool .
…
Use scenario summary :
Objects that are instantiated frequently and then destroyed , Using singleton mode can improve performance .
Frequently used objects , But instantiation takes time or resources , Such as database connection pool , Use singleton mode , Can improve performance , Reduce resource corruption .
When using control resources such as thread pools , Use singleton mode , It can facilitate the communication between resources .
An excerpt from :https://www.nowcoder.com/test/question/done?tid=57875117&qid=304933#summary
边栏推荐
- PCL eigen introduction and simple use
- 学习open62541 --- [66] UA_String的生成方法
- PCL point cloud to depth image
- JSP webshell免杀——JSP的基础
- Uncover the secrets of Huawei application market application statistics
- [quick application] there are many words in the text component. How to solve the problem that the div style next to it will be stretched
- Use of vscode tool
- HDU1234 开门人和关门人(水题)
- How to use ide to automatically sign and debug Hongmeng application
- Dialogue Wu Gang: why do I believe in the rise of "big country brands"?
猜你喜欢
随机推荐
【AppLinking实战案例】通过AppLinking分享应用内图片
One trick to quickly realize custom application titlebar
洛谷 P1892 [BOI2003]团伙(并查集变种 反集)
Analysis of hot spots in AI technology industry
Use Huawei performance management service to configure the sampling rate on demand
How to transfer event objects and user-defined parameters simultaneously in Huawei express applications
【ARK UI】HarmonyOS ETS的启动页的实现
集成学习概览
【快应用】Win7系统使用华为IDE无法运行和调试项目
二叉树专题--AcWing 1589. 构建二叉搜索树
flink二开,实现了个 batch lookup join(附源码)
HDU1234 开门人和关门人(水题)
TIPC Cluster5
Special topic of binary tree -- Logu p1229 traversal problem (the number of traversals in the middle order is calculated when the pre and post order traversals of the multiplication principle are know
[applinking practical case] share in app pictures through applinking
TIPC Service and Topology Tracking4
K-d tree and octree of PCL
JSP webshell免杀——JSP的基础
2022爱分析· 国央企数字化厂商全景报告
JSP webshell free -- webshell free








