当前位置:网站首页>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 …
边栏推荐
- Phpcms prompt message page Jump to showmessage
- libvirt 中体验容器
- 2022年中南大学夏令营面试经验
- Stm32hal library upgrades firmware based on flash analog U disk (detailed explanation)
- 《剑指offer 04》二维数组查找
- 鸿蒙第四次培训
- How to clean up v$rman_ backup_ job_ Details view reports error ora-02030
- Machine learning 3.2 decision tree model learning notes (to be supplemented)
- JGG专刊征稿:时空组学
- C language utf8toutf16 (UTF-8 characters are converted to hexadecimal encoding)
猜你喜欢

The tutor put forward 20 pieces of advice to help graduate students successfully complete their studies: first, don't plan to take a vacation

Gut | Yu Jun group of the Chinese University of Hong Kong revealed that smoking changes intestinal flora and promotes colorectal cancer (do not smoke)

软考中级软件设计师该怎么备考

Viewing binary bin files with notepad++ editor

Web security summary

How to get started embedded future development direction of embedded

PHP server interacts with redis with a large number of close_ Wait analysis

Multi dimensional monitoring: the data base of intelligent monitoring

《剑指offer 04》二维数组查找

软件测试周刊(第78期):你对未来越有信心,你对现在越有耐心。
随机推荐
R语言使用原生包(基础导入包、graphics)中的hist函数可视化直方图(histogram plot)
Viewing binary bin files with notepad++ editor
836. 合并集合(DAY 63)并查集
Application of high-precision indoor positioning technology in safety management of smart factory
导师对帮助研究生顺利完成学业提出了20条劝告:第一,不要有度假休息的打算.....
2022 东北四省赛 VP记录/补题
如何将数字字符串转换为整数
Cacti监控Redis实现过程
程序员的创业陷阱:接私活
DNS多点部署IP Anycast+BGP实战分析
2022年湖南工学院ACM集训第二次周测题解
Redis things
CSRF
Go语言实现静态服务器
repo ~ 常用命令
Mmc5603nj geomagnetic sensor (Compass example)
R language uses the aggregate function to calculate the mean value (sum) of dataframe data grouping aggregation without setting na The result of RM calculation. If the group contains the missing value
DS90UB949
previous permutation lintcode51
R语言使用gridExtra包的grid.arrange函数将ggplot2包的多个可视化图像横向组合起来,ncol参数自定义组合图列数、nrow参数自定义组合图行数