当前位置:网站首页>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
边栏推荐
猜你喜欢
加密压缩文件解密技巧
如何使用MITMPROXy
Contest3147 - game 38 of 2021 Freshmen's personal training match_ E: Listen to songs and know music
Memcached installation
Invalid operation: Load into table ‘sources_ orderdata‘ failed. Check ‘stl_ load_ errors‘ system table
浏览器原理思维导图
Eco express micro engine system has supported one click deployment to cloud hosting
Redis key value database [primary]
Regular expression summary
Unity shader learning notes (3) URP rendering pipeline shaded PBR shader template (ASE optimized version)
随机推荐
Spark overview
Community theory | kotlin flow's principle and design philosophy
Bgp Routing preference Rules and notice Principles
ESP8266与STC8H8K单片机联动——天气时钟
Error creating bean with name 'instanceoperatorclientimpl' defined in URL when Nacos starts
Data playback partner rviz+plotjuggler
加密压缩文件解密技巧
LeetCode 78. 子集
BGP中的状态机
LeetCode 27. 移除元素
锐捷EBGP 配置案例
Scheme and implementation of automatic renewal of token expiration
Contest3147 - game 38 of 2021 Freshmen's personal training match_ 1: Maximum palindromes
Little bear sect manual query and ADC in-depth study
LeetCode 39. Combined sum
Redis Key-Value数据库【初级】
LeetCode 283. Move zero
Ros2 --- lifecycle node summary
数据回放伴侣Rviz+plotjuggler
Contest3147 - game 38 of 2021 Freshmen's personal training match_ E: Listen to songs and know music