当前位置:网站首页>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 1589 Building binary search tree
- 【快应用】Win7系统使用华为IDE无法运行和调试项目
- 【AGC】如何解决事件分析数据本地和AGC面板中显示不一致的问题?
- [SUCTF2018]followme
- MySQL environment configuration
- PCL之K-d树与八叉树
- Shell programming 01_ Shell foundation
- [applinking practical case] share in app pictures through applinking
- 【AGC】构建服务3-认证服务示例
- 学习open62541 --- [66] UA_String的生成方法
猜你喜欢

Hdu1228 a + B (map mapping)

HDU1234 开门人和关门人(水题)

Special topic of binary tree -- acwing 18 Rebuild the binary tree (construct the binary tree by traversing the front and middle order)
![[in simple terms, play with FPGA learning 3 ----- basic grammar]](/img/f0/0204fa5197033877dc0758203253ae.png)
[in simple terms, play with FPGA learning 3 ----- basic grammar]

Disassembling Meitu SaaS: driving the plane to change the engine

二叉树专题--AcWing 1589. 构建二叉搜索树

One trick to quickly realize custom application titlebar

How to implement tabbar title bar with list component

集成学习概览
![[play with FPGA learning 4 in simple terms ----- talk about state machine design]](/img/e0/95f8b8c5116c57455e54ad12372f12.png)
[play with FPGA learning 4 in simple terms ----- talk about state machine design]
随机推荐
JSP webshell免杀——JSP的基础
Special topic of binary tree -- acwing 3384 Binary tree traversal (known preorder traversal, while building a tree, while outputting middle order traversal)
Set the playback speed during the playback of UOB equipment
JSP webshell免殺——JSP的基礎
软件产品管理系统有哪些?12个最佳产品管理工具盘点
TIPC Getting Started6
V2X-Sim数据集(上海交大&纽约大学)
TIPC Cluster5
PCL extracts a subset from a point cloud
长投学堂上面的账户安全吗?
QT学习日记7——QMainWindow
【付费推广】常见问题合集,推荐榜单FAQ
力扣(LeetCode)182. 查找重复的电子邮箱(2022.07.01)
MySQL keyword
洛谷 P5536 【XR-3】核心城市(贪心 + 树形 dp 寻找树的中心)
Record attributeerror: 'nonetype' object has no attribute 'nextcall‘
Special topic of binary tree -- acwing 18 Rebuild the binary tree (construct the binary tree by traversing the front and middle order)
flink二开,实现了个 batch lookup join(附源码)
PCL point cloud to depth image
Appgallery connect scenario development practice - image storage and sharing