当前位置:网站首页>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 …
边栏推荐
猜你喜欢
Web security summary
Redis things
Kubernetes 三打探针及探针方式
《剑指offer 03》数组中重复的数字
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)
Gut | Yu Jun group of the Chinese University of Hong Kong revealed that smoking changes intestinal flora and promotes colorectal cancer (do not smoke)
ArcGIS应用(二十一)Arcmap删除图层指定要素的方法
The world's most popular font editor FontCreator tool
多维度监控:智能监控的数据基础
随机推荐
R语言使用gridExtra包的grid.arrange函数将lattice包的多个可视化图像横向组合起来,ncol参数自定义组合图列数、nrow参数自定义组合图行数
. \vmware-vdiskmanager. exe -k “c:\\xxxxx.vmdk”
STL教程10-容器共性和使用场景
GCC compilation process and dynamic link library and static link library
Uniapp implementation Click to load more
How to make others fear you
抓包整理外篇fiddler———— 会话栏与过滤器[二]
DS90UB949
导师对帮助研究生顺利完成学业提出了20条劝告:第一,不要有度假休息的打算.....
在CoreOS下部署WordPress实例教程
P3250 [HNOI2016] 网络 + [NECPC2022] F.Tree Path 树剖+线段树维护堆
Asyncio warning deprecationwarning: there is no current event loop
Analysis of EPS electric steering system
uniapp实现点击加载更多
Viewing binary bin files with notepad++ editor
MySQL searches and sorts out common methods according to time
Phpcms prompt message page Jump to showmessage
Redis things
STL教程8-map
POI excel cell wrap