当前位置:网站首页>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 .
边栏推荐
- Php OSS file read and write file, workerman Generate Temporary file and Output Browser Download
- How to protect biological privacy in the AI era? Overview of the latest "privacy enhancement technology in biometrics" of the Autonomous University of Madrid, comprehensively detailing the biometric p
- System design idea of time traceability
- UART communication (STM32F103 library function)
- Power supply noise analysis
- 佛祖保佑 永无BUG
- cdc+mysql connector从维表中join的日期时间字段会被+8:00,请问阿里云托管的
- [leetcode] rotation series (array, matrix, linked list, function, string)
- High dimension low code: component rendering sub component
- The efficiency of okcc call center data operation
猜你喜欢
![[leetcode] rotation series (array, matrix, linked list, function, string)](/img/9e/079311df16fa8e28708f4e050e531f.png)
[leetcode] rotation series (array, matrix, linked list, function, string)

企业网络管理员必备的故障处理系统

Necessary fault handling system for enterprise network administrator

Drawing DEM with GEE gracefully

UART communication (STM32F103 library function)

60 个神级 VS Code 插件!!

Starring develops httpjson access point + Database

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

Mq-2 smoke concentration sensor (STM32F103)

Steering gear control (stm32f103c8t6)
随机推荐
Unityshader world coordinates do not change with the model
Volcano成Spark默认batch调度器
ls 常用参数
Vs2017 setting function Chinese Notes
全链路业务追踪落地实践方案
Using alicloud RDS for SQL Server Performance insight to optimize database load - first understanding of performance insight
技术实现 | Apache Doris 冷热数据存储(一)
Introduction to smart contract security audit delegatecall (2)
ArrayList源码解析
How do programmers do we media?
LCD12864 (ST7565P) Chinese character display (STM32F103)
Tkde2022: Dialogue recommendation system based on knowledge enhanced sampling
How to use JWT authentication in thinkphp6
Application practice | massive data, second level analysis! Flink+doris build a real-time data warehouse scheme
物联网?快来看 Arduino 上云啦
R for Data Science (notes) -- data transformation (used by filter)
一文理解OpenStack网络
BSS应用程序云原生部署的8大挑战
企业网络管理员必备的故障处理系统
Will the CDC read out of order when I use SQL