当前位置:网站首页>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
边栏推荐
- Special topic of binary tree -- acwing 18 Rebuild the binary tree (construct the binary tree by traversing the front and middle order)
- HDU1236 排名(结构体排序)
- TIPC Getting Started6
- [AGC] build service 3 - authentication service example
- Record attributeerror: 'nonetype' object has no attribute 'nextcall‘
- 【深入浅出玩转FPGA学习4----漫谈状态机设计】
- Convert yv12 to rgb565 image conversion, with YUV to RGB test
- 实验电镜距离测量之Matlab处理
- Binary tree topic -- Luogu p3884 [jloi2009] binary tree problem (DFS for binary tree depth BFS for binary tree width Dijkstra for shortest path)
- 计算序列之和
猜你喜欢
Uncover the secrets of Huawei application market application statistics
JVM之垃圾回收器
华为AppLinking中统一链接的创建和使用
QT学习日记8——资源文件添加
Special topic of binary tree -- acwing 3384 Binary tree traversal (known preorder traversal, while building a tree, while outputting middle order traversal)
华为游戏初始化init失败,返回错误码907135000
JSP webshell免杀——webshell免杀
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
Read H264 parameters from mediarecord recording
JSP webshell free -- the basis of JSP
随机推荐
二叉树专题--AcWing 1497. 树的遍历(利用后、中序遍历,构建二叉树)
Binary tree topic -- p1030 [noip2001 popularization group] find the first order
TIPC Getting Started6
PCL 点云转深度图像
三.芯片启动和时钟系统
Special topic of binary tree -- acwing 18 Rebuild the binary tree (construct the binary tree by traversing the front and middle order)
一招快速实现自定义快应用titlebar
Summary of cases of players' disconnection and reconnection in Huawei online battle service
学习open62541 --- [66] UA_String的生成方法
PCL Eigen介绍及简单使用
The URL in the RTSP setup header of the axis device cannot take a parameter
Jsp webshell Free from killing - The Foundation of JSP
洛谷 P1892 [BOI2003]团伙(并查集变种 反集)
正则及常用公式
力扣(LeetCode)182. 查找重复的电子邮箱(2022.07.01)
二叉树专题--AcWing 47. 二叉树中和为某一值的路径(前序遍历)
如何使用IDE自动签名调试鸿蒙应用
二叉树专题--洛谷 P1229 遍历问题(乘法原理 已知前、后序遍历求中序遍历个数)
VSCode工具使用
js数组常用方法