当前位置:网站首页>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 .
边栏推荐
- ls 常用参数
- [leetcode] rotation series (array, matrix, linked list, function, string)
- 微信小程序轮播图怎么自定义光标位置
- At present, only CDC monitors Mysql to get the data of new columns. Sqlserver can't, can it
- 【Go语言刷题篇】Go从0到入门4:切片的高级用法、初级复习与Map入门学习
- How to customize cursor position in wechat applet rotation chart
- Why useevent is not good enough
- 我链接mysql 报这个错 是啥意思呀?
- mysql binlog 数据源配置文档麻烦分享一下
- 程序员大部分时间不是写代码,而是。。。
猜你喜欢

Starring develops httpjson access point + Database

Working for 6 years with a monthly salary of 3W and a history of striving for one PM

Write a positive integer to the node and return a floating-point number multiplied by 0.85 when reading the node

PHP OSS file reads and writes files, and workman generates temporary files and outputs them to the browser for download

Vs2017 add header file path method

制造业项目MDM主数据项目实施心得

Source code analysis of ArrayList

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

Internet of things? Come and see Arduino on the cloud
![[R tidyverse] use of select verb](/img/2d/768391bc6ec497432915024bc90842.jpg)
[R tidyverse] use of select verb
随机推荐
Server lease error in Hong Kong may lead to serious consequences
Multi segment curve temperature control FB (SCL program) of PLC function block series
Sr-gnn shift robot gnns: overlapping the limitations of localized graph training data
Some small requirements for SQL Engine for domestic database manufacturers
Unity移动端游戏性能优化简谱之 以引擎模块为划分的CPU耗时调优
Ls common parameters
Example analysis of corrplot related heat map beautification in R language
华为机器学习服务语音识别功能,让应用绘“声”绘色
Interpreting harmonyos application and service ecology
BSS应用程序云原生部署的8大挑战
Write a positive integer to the node and return a floating-point number multiplied by 0.85 when reading the node
Volcano becomes spark default batch scheduler
Application DDoS attack principle and defense method
finkcdc支持sqlserver2008么?
php OSS文件读取和写入文件,workerman生成临时文件并输出浏览器下载
Why is nodejs so fast?
IBPS开源表单设计器有什么功能?
Multi cloud mode is not a "master key"
Understanding openstack network
Preliminary study nuxt3