当前位置:网站首页>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 .
边栏推荐
- Experience of MDM master data project implementation for manufacturing projects
- Obstacle avoidance sensor module (stm32f103c8t6)
- mysql binlog 数据源配置文档麻烦分享一下
- Capacitive inching touch switch module control (stm32f103c8t6)
- 佛祖保佑 永无BUG
- Understanding openstack network
- starring V6平台开发接出点流程
- The script implements the automated deployment of raid0
- 全链路业务追踪落地实践方案
- 应用实践 | 海量数据,秒级分析!Flink+Doris 构建实时数仓方案
猜你喜欢

敏捷之道 | 敏捷开发真的过时了么?

High dimension low code: component rendering sub component

Zadig + cave Iast: let safety dissolve in continuous delivery

60 divine vs Code plug-ins!!

Starring develops httpjson access point + Database

企业网络管理员必备的故障处理系统
![subject may not be empty [subject-empty]](/img/6b/9b57a7ed3ab086036cb6dfe0b31de4.png)
subject may not be empty [subject-empty]

Mqtt protocol usage of LabVIEW

SaltStack State状态文件配置实例

Full link service tracking implementation scheme
随机推荐
Volcano becomes spark default batch scheduler
Fabric 账本数据块结构解析(一):如何解析账本中的智能合约交易数据
我链接mysql 报这个错 是啥意思呀?
R语言 4.1.0软件安装包和安装教程
Unity mobile game performance optimization spectrum CPU time-consuming optimization divided by engine modules
Buddha bless you that there will never be a bug
Real time rendering: the difference between real-time, offline, cloud rendering and hybrid rendering
starring开发HttpJson接入点+数据库
制造业项目MDM主数据项目实施心得
Xiaobai, let me ask you guys, is MySQL binlog extracted by CDC in strict order
How to use JWT authentication in thinkphp6
西北工业大学遭黑客攻击?双因素认证改变局面!
想问下 pgsql cdc 账号同一个 多个 task 会有影响吗,我现在3个task 只有一个 有
60 个神级 VS Code 插件!!
Full link service tracking implementation scheme
What are the functions of IBPs open source form designer?
60 divine vs Code plug-ins!!
Sr-gnn shift robot gnns: overlapping the limitations of localized graph training data
Unity移动端游戏性能优化简谱之 以引擎模块为划分的CPU耗时调优
Dataworks development ODPs SQL development production environment automatic completion of ProjectName