当前位置:网站首页>Concurrent programming - singleton
Concurrent programming - singleton
2022-07-03 11:46:00 【A programmer in a wig】
Concurrent programming - Single case
Say what's in front of you
Today's article is very short , But it's classic , It's worth reading every word carefully …
As I said at the beginning , We need to tidy up some java Learning documents for concurrent programming , This is the eighth article : The singleton pattern . This article mainly talks about the scenarios where several implementation methods of single examples have been applied .
On and off
A little understanding
Professional explanation : Singleton is to ensure that there is only one instance of a class , And there is an access point to get this instance globally .
Simply put, a class can only create one instance , Whenever you use this class, the instance object is the same .
Basically, it reduces the consumption of the creation and destruction of this class of objects .
Um. !
Think about , If a class has only one instance , It must not be created casually , So the key code of the singleton class is that the constructor is private , It is not allowed to create anywhere else .
The advantages of singleton are very clear : Because there's only one instance , Therefore, the memory overhead is reduced , Especially when creating and destroying, it reduces the waste of resources . Avoid multiple use of resources .
What are the disadvantages of single cases : No interface , Cannot inherit , Conflict with single responsibility principle , A class should only care about internal logic , But I don't care how to instantiate it outside .
Single example usage scenario
- Connection pool : The connection pool of a data source in a system is often an instance .
- Thread pool : ditto .
- Counter : You don't need to add to the database every time you refresh , Cache it first with a singleton
- Create class objects that consume too many resources at one time .
Implementation of single case
Single case has 7 Type of implementation
The way 1: Thread unsafe lazy mode
Serve directly :
- The constructor is privatized
- Provide static private instance objects of this class as member variables
- Provide public static methods to obtain this class of objects
/** * @author A programmer in a wig */
public class Singleton {
// The constructor is privatized
private Singleton(){
}
// Private static current class object as member variable
private static Singleton instance;
// Static public method that can get the current class instance object
public static Singleton getInstance(){
// Judge instance Whether there is , If it exists, go back to , If it doesn't exist, create it
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
The above procedure is very simple : If you want to get Singleton The instance object of class can be written like this Singleton.getInstance()
You'll find that :
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2);// true forehead ..... Do it a few more times , It could be false
explain :
- This method was not created at the beginning instance, It's created the first time it's used , This is the essence of the lazy man mode . It effectively realizes delayed loading . Save memory .
- This approach is not thread safe , There may be hidden dangers .
- If the thread A call getInstance Method , Determine the instance by null, Preparing to create object , result CPU No resources , So I stopped for a while , This is a thread B Also called getInstance Method , The result is that instance Is still null, So I created instance object . After that thread A Start execution , Threads A No more judgment , Create directly instance object , In this way, the object of this class is created twice .
The way 2: Thread safe lazy mode
Serve :
- The constructor is privatized
- Provide static private instance objects of this class as member variables
- Provide public static and synchronous methods to obtain this class of objects
/** * @author A programmer in a wig */
public class Singleton1 {
// The constructor is privatized
private Singleton1(){
}
// Private static current class object as member variable
private static Singleton1 instance;
// Static public method that can get the current class instance object
public static synchronized Singleton1 getInstance(){
// Judge instance Whether there is , If it exists, go back to , If it doesn't exist, create it
if(instance == null){
instance = new Singleton1();
}
return instance;
}
}
This test is very simple :
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
System.out.println(s1 == s2);// true forehead ... No matter how many times it is executed here true
explain :
- This way is obviously in getInstance The method of adding synchronized Modifier , In this way, the problem of thread safety is successfully avoided .
- But we all know that once locked , The efficiency of the program will be slightly reduced ( But what? , stay JDK1.6 after synchronized Optimized , If there is no large number of concurrency, the efficiency impact is not significant )
The way 3: Starving model
This is the key to the hungry man model “ hungry ” word . forehead … I remember when I was in a hurry to eat , My dear old mother said :“ Eat slowly , It's like starving to death ”. Fortunately, my old mother will say the same about me now . Ha ha ha ha ha ha ha ....
Get down to business : Hungry man mode is to directly create instance objects at the beginning
- The constructor is privatized
- Provide static private instance objects of this class as member variables , And directly instantiate
- Provide public static methods to obtain this class of objects
/** * @author A programmer in a wig */
public class Singleton2 {
// The constructor is privatized
private Singleton2(){
}
// Private static current class object as member variable
private static Singleton2 instance = new Singleton2();
// Static public method that can get the current class instance object
public static synchronized Singleton2 getInstance(){
// Judge instance Whether there is , If it exists, go back to , If it doesn't exist, create it
if(instance == null){
instance = new Singleton2();
}
return instance;
}
}
Hungry man mode is really a little hungry , Created from the beginning .
But if , Not hungry now , Is it a waste to cook the rice directly .
So the problem of hungry man mode is that if you create class objects at the beginning , But this object will not be used for a long time , Then it's a waste of resources .
So , It still depends on the actual use scenario .
The way 4: Double check lock / Double check lock
Program , We must pursue efficiency and save resources . So we hope that the method of creating objects in simple profit mode is also efficient .
But once we lock the method, the execution efficiency of the method will inevitably be reduced , So double check lock may be a good choice , It can relatively improve the efficiency of the program , And thread safety .
The concrete realization is :
/** * @author A programmer in a wig */
public class Singleton3 {
// The constructor is privatized
private Singleton3(){
}
// Private static current class object as member variable
private static Singleton3 instance;
// Static public method that can get the current class instance object
public static Singleton3 getInstance(){
// Judge instance Whether there is , If it exists, go back to , If it doesn't exist, create it
if (instance==null) {
// locked
synchronized (Singleton3.class) {
// Judge again instance Whether there is , If it exists, go back to , If it doesn't exist, create it
if (instance == null) {
instance = new Singleton3();
}
}
}
return instance;
}
}
The way 5: Static inner class
The implementation of static inner classes is also called registration . What is the situation :
Serve directly :
/** * @author A programmer in a wig */
public class Singleton4 {
// The constructor is privatized
private Singleton4(){
}
// Prepare a static inner class
private static class SingletonHolder{
// Declare and instantiate an instance object of an external simple interest class , And set to constant .
private final static Singleton4 INSTANCE = new Singleton4();
}
// Static public method that can get the current class instance object
public static Singleton4 getInstance(){
// Directly return the member constants of the inner class
return SingletonHolder.INSTANCE;
}
}
What's the use of this method ?
- In no call getInstance Before method , Static internal will delay loading, that is, the creation of objects will delay .
- utilize classloader The mechanism of ensures that the instance creation is definitely single threaded .
- Of course, if you don't want the instance object to be loaded late, it's better to use hungry man mode .
The way 6: enumeration
This method is too simple , Also understand ( Of course, you must first know what enumeration is ). So I won't explain more .
public enum Singleton {
INSTANCE;
public void whateverMethod() {
}
}
This is the case with the simple interest model .
There are other things related to concurrent programming , I will keep updating , Welcome to your attention .
I am a ” Starting point programming “ Of " A programmer in a wig " Welcome to your attention … Welcome comments .....
Starting point programming - You are my future …
边栏推荐
- typeScript
- 牛牛的组队竞赛
- Hongmeng fourth training
- 多维度监控:智能监控的数据基础
- The LINQ expression node type 'ArrayIndex' is not supported in LINQ to Entities
- 2022年湖南工学院ACM集训第二次周测题解
- Nestjs configuration service, configuring cookies and sessions
- Linear table sequence table comprehensive application problem p18
- 解决msvcp120d.dll和msvcr120d.dll缺失
- Excel quick cross table copy and paste
猜你喜欢

Viewing binary bin files with notepad++ editor

Analysis of EPS electric steering system

Use typora to draw flow chart, sequence diagram, sequence diagram, Gantt chart, etc. for detailed explanation

Numpy np. Max and np Maximum implements the relu function

2022 东北四省赛 VP记录/补题

Qt+VTK+OCCT读取IGES/STEP模型

一文搞懂Go语言Context

(database authorization - redis) summary of unauthorized access vulnerabilities in redis

Xml的(DTD,xml解析,xml建模)

cgroup简介
随机推荐
在CoreOS下部署WordPress实例教程
ASP.NET-酒店管理系統
How should intermediate software designers prepare for the soft test
The tutor put forward 20 pieces of advice to help graduate students successfully complete their studies: first, don't plan to take a vacation
简单工厂和工厂方法模式
This article explains the complex relationship between MCU, arm, MCU, DSP, FPGA and embedded system
POI excel cell wrap
Cacti监控Redis实现过程
Yintai department store ignites the city's "night economy"
ASP. Net hotel management system
Asyncio warning deprecationwarning: there is no current event loop
C language AES encryption and decryption
Hongmeng third training (project training)
Kubernetes 三打探针及探针方式
利用Zabbix动态监控磁盘I/O
How to make others fear you
(数据库提权——Redis)Redis未授权访问漏洞总结
PHP Basics
R语言使用data.table包进行数据聚合统计计算滑动窗口统计值(Window Statistics)、计算滑动分组中位数(median)并合并生成的统计数据到原数据集中
Excel快速跨表复制粘贴