当前位置:网站首页>The difference between the lazy man mode and the hungry man mode
The difference between the lazy man mode and the hungry man mode
2022-06-24 19:32:00 【Jade label】
https://www.runoob.com/design-pattern/singleton-pattern.html
Just watch the realization of the lazy and hungry in the rookie .
Mainly : Lazy people support lazy loading , Load only when used for the first time , Avoid memory waste , There are thread safe and unsafe , Thread safe can be used in multithreading , Hungry people do not support lazy loading , Class initialization for loading , Waste of memory , But thread installation . For double check lock / Double check lock , Support lazy loading , Support thread safety , Optimal scheme .
1、 Slacker type , Thread unsafe
whether Lazy initialization : yes
Is multithreading safe : no
Difficulty of realization : easy
describe : This is the most basic way to achieve , The biggest problem with this implementation is that it doesn't support multithreading . Because there is no lock synchronized, So strictly speaking, it's not a singleton pattern .
This way, lazy loading Obviously , Thread safety is not required , Multithreading doesn't work .
example
public class Singleton { private static Singleton instance; private Singleton (){} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
The following several implementation methods all support multithreading , But there are differences in performance .
2、 Slacker type , Thread safety
whether Lazy initialization : yes
Is multithreading safe : yes
Difficulty of realization : easy
describe : This way has a good lazy loading, Can work well in multithreading , however , Efficiency is very low ,99% There is no need to synchronize .
advantage : The first call initializes , Avoid memory waste .
shortcoming : Must be locked. synchronized To guarantee the single case , But locking can affect efficiency .
getInstance() Performance is not critical for applications ( This method is not used frequently ).
example
public class Singleton { private static Singleton instance; private Singleton (){} public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
3、 Hungry Chinese style
whether Lazy initialization : no
Is multithreading safe : yes
Difficulty of realization : easy
describe : This way is more commonly used , But it is easy to produce garbage objects .
advantage : No locks , The efficiency of execution will improve .
shortcoming : Class is initialized when it is loaded , Waste of memory .
It's based on classloader The mechanism avoids the synchronization problem of multithreading , however ,instance Instantiate at class load time , Although there are many reasons for class loading , In singleton mode, most of them call getInstance Method , But I'm not sure there are other ways ( Or other static methods ) Causes the class to load , This time initialization instance Obviously not lazy loading The effect of .
example
public class Singleton { private static Singleton instance = new Singleton(); private Singleton (){} public static Singleton getInstance() { return instance; } }
4、 Double check lock / Double check lock (DCL, namely double-checked locking)
JDK edition :JDK1.5 rise
whether Lazy initialization : yes
Is multithreading safe : yes
Difficulty of realization : More complicated
describe : This method adopts double lock mechanism , It is safe and can maintain high performance in multithreading .
getInstance() Performance is critical to the application .
example
public class Singleton { private volatile static Singleton singleton; private Singleton (){} public static Singleton getSingleton() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }
Not to mention the inner classes and enumerations ( Understanding is good. ).
5、 Registration form / Static inner class
whether Lazy initialization : yes
Is multithreading safe : yes
Difficulty of realization : commonly
describe : This way can achieve the same effect of double lock , But it's easier to achieve . Use delay initialization for static fields , This method should be used instead of double locking . This method only applies to the static domain , The double check lock mode can be used when the instance domain needs to delay initialization .
This approach also takes advantage of classloader Mechanism to ensure initialization instance There is only one thread , It follows the 3 The difference is : The first 3 There's only one way Singleton Class is loaded , that instance It will be instantiated ( Don't reach lazy loading effect ), And this way is Singleton Class is loaded ,instance Not necessarily initialized . because SingletonHolder Class is not actively used , Only by explicitly calling getInstance When the method is used , To explicitly load SingletonHolder class , To instantiate instance. Imagine , If you instantiate instance It's a drain on resources , So I want it to delay loading , On the other hand , I don't want to be in Singleton The class is instantiated when it is loaded , Because there's no guarantee Singleton Classes may also be actively used elsewhere to be loaded , So this is the time to instantiate instance Clearly not appropriate . This is the time , This way is better than 3 That's a reasonable way .
example
public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton (){} public static final Singleton getInstance() { return SingletonHolder.INSTANCE; } }
6、 enumeration
JDK edition :JDK1.5 rise
whether Lazy initialization : no
Is multithreading safe : yes
Difficulty of realization : easy
describe : This implementation has not been widely adopted , But this is the best way to implement the singleton pattern . It's simpler , Automatic support for serialization mechanism , Absolutely prevent multiple instantiations .
This way is Effective Java author Josh Bloch Ways to advocate , It not only avoids the multithreaded synchronization problem , It also automatically supports serialization mechanism , Prevents deserialization from recreating new objects , Absolutely prevent multiple instantiations . however , because JDK1.5 After that enum characteristic , It feels strange to write in this way , In practice , Rarely use .
Cannot pass reflection attack To call the private constructor .
example
public enum Singleton { INSTANCE; public void whateverMethod() { } }
Wise remark of an experienced person : In general , It is not recommended to use 1 Species and 2 A lazy way , It is recommended to use section 3 The way of starving people . Only if we want to realize lazy loading In effect , Will use the 5 How to register . If it comes to deserialization when creating objects , You can try using section 6 There are several ways to enumerate . If there are other special needs , Consider using section 4 Double lock mode .
边栏推荐
- LCD12864 (ST7565P) Chinese character display (STM32F103)
- 怎么使用R包ggtreeExtra绘制进化树
- R语言corrplot相关热图美化实例分析
- Does version 2.2.0 support dynamic addition of MySQL synchronization tables
- Introduction to smart contract security audit delegatecall (2)
- cdc+mysql connector从维表中join的日期时间字段会被+8:00,请问阿里云托管的
- [leetcode] rotation series (array, matrix, linked list, function, string)
- System design idea of time traceability
- Using alicloud RDS for SQL Server Performance insight to optimize database load - first understanding of performance insight
- Network security review office starts network security review on HowNet
猜你喜欢

Volcano becomes spark default batch scheduler

R for Data Science (notes) -- data transformation (used by filter)

Zadig + cave Iast: let safety dissolve in continuous delivery

Interpreting harmonyos application and service ecology
![[leetcode] rotation series (array, matrix, linked list, function, string)](/img/9e/079311df16fa8e28708f4e050e531f.png)
[leetcode] rotation series (array, matrix, linked list, function, string)

Technology implementation | Apache Doris cold and hot data storage (I)

数字孪生行业案例:智慧港口数字化

微信小程序轮播图怎么自定义光标位置

Kubernetes集群部署

R语言 4.1.0软件安装包和安装教程
随机推荐
starring V6平台开发接出点流程
Fabric 账本数据块结构解析(一):如何解析账本中的智能合约交易数据
60 divine vs Code plug-ins!!
Real time rendering: the difference between real-time, offline, cloud rendering and hybrid rendering
Network security review office starts network security review on HowNet
Write a positive integer to the node and return a floating-point number multiplied by 0.85 when reading the node
R for Data Science (note) -- data transformation (select basic use)
Starring V6 platform development take out point process
Sr-gnn shift robot gnns: overlapping the limitations of localized graph training data
华为机器学习服务语音识别功能,让应用绘“声”绘色
If the programmer tells the truth during the interview
Mq-2 smoke concentration sensor (STM32F103)
Will the CDC read out of order when I use SQL
Freeswitch uses origin to dialplan
试驾 Citus 11.0 beta(官方博客)
R语言corrplot相关热图美化实例分析
敏捷之道 | 敏捷开发真的过时了么?
多云模式并非“万能钥匙”
Mqtt protocol usage of LabVIEW
LCD1602 string display (STM32F103)