当前位置:网站首页>Singleton mode compilation
Singleton mode compilation
2022-07-02 06:13:00 【Radish goo】
Single case "> What is a single example
The single example is to ensure a memory / There is only one instance of a class in the process , And provide a global access point to access it .
- Memory / There is only one instance in the process
- Thread safety
- performance optimization
- Prevent serialization from generating new objects
Write a singleton pattern
1、 Starving model
public class Singleton {
// Starving model
private static Singleton singleton=new Singleton();
// Private constructor
private Singleton() {}
//
public static Singleton getSingleton() {
return singleton;
}
} At the start of the project , Put the object directly new come out , Whether he uses it or not ;
2、 The sluggard model
When needed , To go to new object
lazy -( Non-thread safety )
public class Singleton {
// The sluggard model
private static Singleton singleton;
private Singleton() {}
public static Singleton getSingleton() {
if (singleton == null) {
Singleton singleton=new Singleton();
}
return singleton;
}
}But in this way , Thread unsafe , It can lead to , When multiple threads trigger , It is possible to create multiple objects ; So we will use thread safe mode later , Lock the corresponding method
lazy -( Thread safety )
public class Singleton {
private Singleton singleton;
private static Singleton() {}
public static synchronized Singleton getSingleton() {
if (singleton == null) {
Singleton singleton=new Singleton();
}
return singleton;
}
}But this lock is on the method , It's heavy , So in order to optimize this content , We need to optimize , Therefore, there is the implementation of double check lock , Just put it on the required code block
Double check lock
In most cases , Synchronized code blocks will not be executed to , Improved program performance .
There is a situation , Two threads ThreadA,ThreadB, If threadA To the first if conditional ,singleton = null;ThreadB Also implemented to if conditional singleton = null, therefore A and B The code in the synchronized code block will be executed in turn . To avoid creating two instances , Therefore, we added if Condition for double inspection .
public class Singleton {
private static Singleton singleton;
private Singleton() {}
public static Singleton getSingleton() {
if (singleton==null) {
synchronized (Singleton.class) {
if (singleton==null) {
Singleton singleton=new Singleton();
}
}
}
return singleton;
}
}hidden danger :
When performing this step , There will be JVM Will reorder instructions ; Originally, our process was
1、 Allocate memory space 2、 Initialize object 3、 Set the memory space pointed to by the current object
But here , There will be the problem of reordering instructions , That is, the step will become
1->3->2, Threads A Up to the third day 3 Step by step , Threads B call getsingleton Method , In judging singleton==null Time is not null, Then return to singleton. But this time singleton Not initialized yet , Threads B Access will be an object that has not been initialized yet . So here we will use volatile keyword , In order to avoid the problem of reordering instructions ; When the reference of the declared object is volatile after , Pseudo code 2、3 Reordering of will be disabled in multithreading !
public class Singleton {
private volatile static Singleton singleton;
private Singleton() {}
public static Singleton getSingleton() {
if (singleton==null) {
synchronized (Singleton.class) {
if (singleton==null) {
Singleton singleton=new Singleton();
}
}
}
return singleton;
}
}
Be careful :
The two main steps :
private Singleton() {}: The construction of privatization
: Through one public Methods , Put this singleton The object is exposed
In this case , A singleton is implemented
边栏推荐
- [C language] screening method for prime numbers
- JWT工具类
- From design delivery to development, easy and efficient!
- Monitoring uplink of VRRP
- LeetCode 83. Delete duplicate elements in the sorting linked list
- Detailed explanation of BGP message
- LeetCode 78. 子集
- servlet的web.xml配置详解(3.0)
- Bgp Routing preference Rules and notice Principles
- 深入了解JUC并发(二)并发理论
猜你喜欢

神机百炼3.52-Prim

ESP8266与STC8H8K单片机联动——天气时钟

Spark overview

Comment utiliser mitmproxy

Invalid operation: Load into table ‘sources_ orderdata‘ failed. Check ‘stl_ load_ errors‘ system table

线性dp(拆分篇)

Data playback partner rviz+plotjuggler

官方零基础入门 Jetpack Compose 的中文课程来啦!

Eco express micro engine system has supported one click deployment to cloud hosting

穀歌出海創業加速器報名倒計時 3 天,創業人闖關指南提前收藏!
随机推荐
Flutter hybrid development: develop a simple quick start framework | developers say · dtalk
经典文献阅读之--Deformable DETR
Data playback partner rviz+plotjuggler
STC8H8K系列汇编和C51实战——串口发送菜单界面选择不同功能
492. Construction rectangle
Spark overview
LeetCode 47. 全排列 II
在uni-app中引入uView
Go learning notes integration
Stc8h8k Series Assembly and c51 Real combat - NIXIE TUBE displays ADC, Key Series port reply Key number and ADC value
Regular expression summary
Picture clipping plug-in cropper js
Web page user step-by-step operation guide plug-in driver js
神机百炼3.52-Prim
线性dp(拆分篇)
Zhuanzhuanben - LAN construction - Notes
格式校验js
Step by step | help you easily submit Google play data security form
浏览器原理思维导图
复杂 json数据 js前台解析 详细步骤《案例:一》