当前位置:网站首页>Single case model of hand tear
Single case model of hand tear
2022-04-21 18:38:00 【Erhao's dream talk】
Some hand tearing questions often encountered during the interview , Usually do not write the interview, the interview has no idea . The common ones are hand tearing simple interest 、 Tear producers and consumers by hand 、 Multiple threads take turns printing and so on .
Single case model
The singleton model involves a single class , This class is responsible for creating its own objects , Also make sure that only a single object is created . This class provides a way to access its unique objects , You can directly access , There is no need to instantiate an object of this class .
Characteristics of single case model :
1、 A singleton class can have only one instance .
2、 The singleton class must create its own unique instance .
3、 The singleton class must provide this instance to all other objects
Key points of singleton mode :
The construction method is not open to the outside world , by private
Ensure that the singleton class has only one object , Especially in multithreading mode
Return singleton objects through static methods or enumerations
Ensure that the singleton class will not recreate new objects during deserialization
Realization way
Hungry Chinese style
Hungry Chinese style will create the required singleton object in advance , You can get it directly when you need it , No need to create . The advantage is convenience 、 Security , Saves creation time , There will be no safety problems when creating threads in advance . The disadvantage is that it may cause a waste of resources , No lazy loading , Because it is impossible to determine whether the singleton will use , May never use , Or it will take a long time to use , Creating ahead of Time wastes resources .
public class Singleton1 {
private static Singleton1 singleton1 = new Singleton1();
private Singleton1(){ }
public static Singleton1 getInstance(){
return singleton1;
}
}
Slacker type
Lazy people wait until they need to create , Will not be created in advance . The advantage is the efficient use of resources , But there may be thread safety issues , Therefore, thread synchronization must be carried out .
private static Singleton2 instance;
private Singleton2(){}
public static synchronized Singleton2 getInstance(){
if(instance == null){instance = new Singleton2();}
return instance;
}
}
It's on it getInstance add to synchronized, Thread synchronization , It's not efficient , Because I don 't care instance Is it created , Thread synchronization will be carried out , Low efficiency . The better thing is to synchronize when it is not created again , There is no need to synchronize after creation , Just go back . The first inspection is as follows instance Not for null, There is no need to perform the following lock initialization operation , So it can reduce synchronized Performance overhead . A second check instance Avoid multiple threads passing through the first one at the same time instance The inspection of .
public class Singleton2 {
private volatile static Singleton2 instance;
private Singleton2(){}
public Singleton2 getInstance(){
if(instance == null){
synchronized (Singleton2.class){
if(instance == null){
instance = new Singleton2();
}
}
}
return instance;
}
}
instance By volatile Keyword modification , Can avoid command rearrangement .new Keyword creates an object divided into 3 Step :
1. by instance Allocate memory space
2. initialization instance
3. by instance Point to the memory address of the allocated memory
JVM Possible instruction rearrangement , If it's normal 1->2->3 In order , Then there must be no problem . But if the instructions are rearranged , Turn into 1->3->2,instance When pointing to the allocated memory address ,instance Initialization is not complete . If other threads enter at this time, get instance, Will judge instance Not null, Judgment has been created , however instance Not instantiated , If you use instance It will cause all kinds of problems . Use volatile By inserting a memory barrier, you can disable JVM Instruction reordering , Ensure normal operation in multi-threaded environment .
Static inner class method to realize singleton
When loading a class , Will initialize static variables 、 Static code block 、 Static methods , But the inner classes and static inner classes will not be loaded . So static inner classes don't load first , Only when static inner classes are used will they be loaded . Class loading ( Whether static inner classes or ordinary classes ),JVM Thread synchronization will be carried out . Therefore, this method can be loaded when necessary instance, And thread safety .
The singleton mode here is to use final keyword , When final Modify variables of reference type , After its initialization, it cannot point to another object , Make sure to initialize only once . meanwhile final Memory semantics also prevent instruction rearrangement , That is, the assignment to this object should be done after initialization .
public class Singleton3 {
public static class SingletonHolder{
private static final Singleton3 instance = new Singleton3();
}
private Singleton3(){}
public static final Singleton3 getInstance(){
return SingletonHolder.instance;
}
}
Enumeration implementation
public enum Singleton4 {
INSTANCE;
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
Use SingletonEnum.INSTANCE Visit , There is no need to define getInstance Method and calling the method .
JVM Uniqueness of enumerated instances , It avoids the ring breaking singleton of deserialization and reflection mechanism mentioned above : Each enumeration type and defined enumeration variable are in JVM All of them are unique . reason : When serializing an enumeration type, it only enumerates the objects name The property is output to the result , When you deserialize it, you pass it java.lang.Enum Of valueOf Method to find an enumeration object by name .
版权声明
本文为[Erhao's dream talk]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204211833338453.html
边栏推荐
猜你喜欢
![[dai4] the entry node of the link in jz23 linked list](/img/80/eca8951f581dc27cce9597af13e47e.png)
[dai4] the entry node of the link in jz23 linked list

Advanced formula 46 of C language: function and macro analysis
Building local canal middleware for data migration -- Inspiration from cache breakdown

ACM纪念日 C语言

Redis三种特殊数据类型——Geospatial地理空间

ACM anniversary C language

Target penetration exercise 72-dc4
每日一博 - Devops全流程

Find the card with equal difference (20 points) C language

数字IC教程之 02 Quartus Prime 和 Modelsim 安装教程
随机推荐
2021-5-1 第一天第一题
每日一博 - Devops全流程
如何用PS制作动图
Pictures and texts teach you how to generate code with one click in idea to improve development efficiency!
Hero King C language
CDF global survey: stagnant software delivery performance
Appium principle and jsonwp protocol analysis of automatic testing of dry goods app
微信QQ支付宝三合一收款二维码实现原理
ACM纪念日 C语言
Win10 uwp asynchronous progress bar
The Renaissance of digital art, the exploration and rise of Digital Collections
The products that were once bought are coming again. It must be right to buy them steadily
[daiy4] jz76 delete duplicate nodes in the linked list (recursion)
A simple and easy-to-use file upload scheme
Assignment and value of WPF RichTextBox
高等数学公式(第5部分)
Target penetration exercise 69-dc1
找出相等差值的卡片 (20 分) C语言
Comment voir la structure zskiplist dans le code source redis
哪路神仙写的421页MySQL高级笔记,涵盖MySQL所有技术!太香了