当前位置:网站首页>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 .
边栏推荐
- Module V
- Saltstack state state file configuration instance
- A detailed explanation of the implementation principle of go Distributed Link Tracking
- 数字孪生行业案例:智慧港口数字化
- Generate the last login user account report of the computer through SCCM SQL
- The efficiency of okcc call center data operation
- R for Data Science (note) -- data transformation (select basic use)
- [leetcode] rotation series (array, matrix, linked list, function, string)
- 对国产数据库厂商提几个关于SQL引擎的小需求
- An accident caused by a MySQL misoperation cannot be withstood by High Availability!
猜你喜欢

Source code analysis of ArrayList

Intel and Microsoft give full play to the potential energy of edge cloud collaboration to promote the large-scale deployment of AI

Zadig + 洞态 IAST:让安全溶于持续交付

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

Network security review office starts network security review on HowNet

Php OSS file read and write file, workerman Generate Temporary file and Output Browser Download

php OSS文件读取和写入文件,workerman生成临时文件并输出浏览器下载

工作6年,月薪3W,1名PM的奋斗史

Unity移动端游戏性能优化简谱之 以引擎模块为划分的CPU耗时调优

starring V6平台开发接出点流程
随机推荐
A detailed explanation of the implementation principle of go Distributed Link Tracking
Huawei machine learning service speech recognition function enables applications to paint "sound" and color
我链接mysql 报这个错 是啥意思呀?
Application DDoS attack principle and defense method
Unityshader world coordinates do not change with the model
How to deal with the problem that the Flink CDC reads MySQL in full and always reports this error
subject may not be empty [subject-empty]
Using alicloud RDS for SQL Server Performance insight to optimize database load - first understanding of performance insight
Obstacle avoidance sensor module (stm32f103c8t6)
Does version 2.2.0 support dynamic addition of MySQL synchronization tables
Xiaobai, let me ask you guys, is MySQL binlog extracted by CDC in strict order
目前是不是只cdc 监控mysql 可以拿到新增列的数据 sqlserver不行是吧
LCD12864 (ST7565P) Chinese character display (STM32F103)
LCD1602 string display (STM32F103)
How to select the ECS type and what to consider?
IBPS开源表单设计器有什么功能?
Starring develops httpjson access point + Database
Unity mobile game performance optimization spectrum CPU time-consuming optimization divided by engine modules
Tkde2022: Dialogue recommendation system based on knowledge enhanced sampling
微信小程序轮播图怎么自定义光标位置