当前位置:网站首页>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语言】简单实现扫雷游戏
- Unity Shader 学习笔记(3)URP渲染管线带阴影PBR-Shader模板(ASE优化版本)
- Mock simulate the background return data with mockjs
- 来自读者们的 I/O 观后感|有奖征集获奖名单
- Verifying downloaded files using sha256 files
- Detailed notes of ES6
- 深入了解JUC并发(二)并发理论
- The real definition of open source software
- Mathematical statistics and machine learning
- Stc8h8k Series Assembly and c51 Real combat - NIXIE TUBE displays ADC, Key Series port reply Key number and ADC value
猜你喜欢
Deep learning classification network -- alexnet
Zabbix Server trapper 命令注入漏洞 (CVE-2017-2824)
From design delivery to development, easy and efficient!
Classic literature reading -- deformable Detr
深入了解JUC并发(二)并发理论
BGP中的状态机
穀歌出海創業加速器報名倒計時 3 天,創業人闖關指南提前收藏!
Little bear sect manual query and ADC in-depth study
数据回放伴侣Rviz+plotjuggler
Introduce uview into uni app
随机推荐
Scheme and implementation of automatic renewal of token expiration
复杂 json数据 js前台解析 详细步骤《案例:一》
神机百炼3.52-Prim
Generic classes and parameterized classes of SystemVerilog
Use some common functions of hbuilderx
Reading classic literature -- Suma++
线性dp(拆分篇)
Lambda 表达式 和 方法引用
Servlet web XML configuration details (3.0)
LeetCode 283. Move zero
LeetCode 39. 组合总和
Web components series (VIII) -- custom component style settings
STC8H8K系列汇编和C51实战——数码管显示ADC、按键串口回复按键号与ADC数值
Zhuanzhuanben - LAN construction - Notes
On Web server
LeetCode 90. 子集 II
LeetCode 77. combination
Unity shader learning notes (3) URP rendering pipeline shaded PBR shader template (ASE optimized version)
51单片机——ADC讲解(A/D转换、D/A转换)
Brain and cognitive neuroscience matlab psychoolbox cognitive science experimental design - experimental design 4