当前位置:网站首页>[multithreading] realize the singleton mode (hungry and lazy) realize the thread safe singleton mode (double validation lock)
[multithreading] realize the singleton mode (hungry and lazy) realize the thread safe singleton mode (double validation lock)
2022-07-01 20:26:00 【51CTO】
Catalog
- The singleton pattern
The singleton pattern
What is singleton mode
Require a class in our code , There can be only one instance , Cannot have multiple instances . Examples are objects . That is, a class can only new An object , You can't new Multiple objects .
This singleton mode , It is very common in practical development , It's also very useful .
Many in development “ Concept ”, Nature is a single case .
such as :
Use JDBC Operating the database , At this time, the database connection can be obtained through the database connection pool database connection
The connection pool can use the singleton mode , Create a unique object .Most things are related to , Only one copy is stored in the server . that , You can use “ The singleton pattern ” To represent .
Two classic implementations of singleton mode
There are two typical implementations in singleton mode :
Starving modelThe sluggard model
Let's talk about the hungry man model through a life example , What is lazy mode .
Wash the dishes :
Case one :
Suppose we have lunch ,The family used 4 A bowl . Then after eating , Wash the bowl right away
This situation , NamelyStarving model
The second case :
At lunch ,The family used 4 A bowl . Then after eating , Put the bowl first , Don't worry about washing
Waiting for dinner at night , The discovery only needs 2 A bowl .
Then we will 4 An unwashed bowl in , Wash out 2 A bowl , Use it . After eating , Put the bowl first , Don't worry about washing .
If you only use one for the next meal , Just wash out 1 A bowlJust how much , Take how much . Not enough , No more
This is it.The sluggard model
But in the computer , It is generally believed that The sluggard model Than The hungry man mode is good . Mainly because The sluggard model More efficient
It's easy to understand : wash 2 individual bowl , It must be better than washing 4 A bowl is easy .
So use a few to wash a few .
According to need , To operate .“ lazy ” This word is general In the computer , It's a compliment .
1. Starving model ( Thread safety )
The hungry man mode class instantiates an object immediately when the class is loadedSo follow up anyway As long as it is strictly used get Method There will be no other instances- It can be seen from the above that
Hungry man mode is thread safeOfHe also has a problem that even if I don't use this class He will also create an instance to occupy our memory This leads to his low efficiencyA single instance of this version cannot have other instance variables , Otherwise, there will still be nonlinear safety problems( The non thread safety problem is A thread caused dirty reading of data by modifying an instance variable )

analysis :
(1) Why thread safe ?
Because it is initialized when the class is loaded ( The first 2 That's ok ), Only one copy. , So it's thread safe .(2) shortcoming
① Not yet used , It wastes memory space .
②new object ( Class loading is not performed , Will execute first , Then execute the member variable + Instance code block + Construction method ), May throw an exception , That is, you haven't called getInstance, An exception is thrown when the class is loaded , Then call later getInstance When the method is used , There will be problems .
2. The sluggard model ( Thread unsafe )
The lazy man model improves the shortcomings of the hungry man model It only lets this class instantiate an object when it is usedAnd after that, you can only get this object- So we generally think that the lazy man mode is better than the hungry man mode
More efficient- however
Lazy mode also has disadvantages. Its thread is not safeThis is in It can be optimized
Because I'm lazy , You make me work , I just started , Otherwise I won't take the initiative ~
Talk is talk : When the class loading , Don't rush to initialize the object , First call , Initialize object , Call again later , Directly return the first created object .
analysis :
Why thread is not safe ?
stay
getInstance() In the method, There are three lines in all Java Code .
And among them instance = new Singleton() Will be decomposed into three lines of bytecode instructions , It is equivalent to concurrent and parallel operations on multiple rows of shared variables , So it's not thread safe .

difference :
Starving model and The sluggard model The only difference :
lie in The timing of creating an instance is different .
Starving model yes When the class loading , establish .The sluggard model yes First use , establish .So the lazy mode is lazier , When not in use , Do not create ; When you use it , Create again .
The purpose of this , NamelySave resources.
In fact, in many other computer scenes , This situation will also be involved .
A typical case :
notepad Such a program ( Notepad software ), It's very slow to open large files .
If , You have to open a 1G Size file , here notepad willTry this 1 G Of Everything is read into memory.
take 1G The amount of data Deposit in Memory , ObviouslyVery slowOf .
Whether you want to or not , All for you .
This is it.Starving model.The problem comes with : These data , Can we really use it all ? Display is unlikely .
Therefore, a lot of resources will be wasted .
Like some other programs , When you open a large file, there is optimization .
Suppose it's also open 1G The file of , But only load the part that can be displayed in this screen first .See where , Where to load . This will not waste space
This is it.The sluggard model
Thread safe singleton mode
1. The sluggard model +synchronized Static synchronization method ( Thread safe but inefficient )
When it comes to making a code thread safe , We naturally think of locking !
But the problem is : Where is the right place to lock ?
In fact, observation is also very good , take if Statement execution to Lock , Make its two operations atomic .
To put it bluntly : Namely if sentence Pack it up “ all in one ”, Just like the previous analysis count++ equally .
Consistency execution finished .

Lock range Be sure to include if sentence !!!
Otherwise it won't work , It looks like this !
Originally, we wanted to read and Write operation , Pack it as a whole ,
But now it's just Lock the write operation , At this time, it's like not locking equally , There is no difference .
Please pay attention ! Not in the code synchronized, It must be thread safe . It needs to see synchronized Location of addition , Be right, too . therefore synchronized Where to write . You can't do it casually .
Come back to , Let's take another look synchronized The object of the lock writes what we should .

Although we do through the above locking operation , It's solved if sentence The atomicity of .
however ! Such a program , There are still several problems !
1. Code execution efficiency
2、 Instruction reordering
Although other threads call again When a singleton thread , Also added synchronized Of .
Slow down the cycle speed , So as to ensure Memory visibility .
however ! There's another problem , Look at the following .
here , We just completed a thread safe singleton mode - The sluggard model
1、 Lock in the right position2、 double if determine3、volatile keyword
2. The sluggard model + Second judgment ( Double check lock , Thread safe and efficient )
usage :
- Double check : Two if.
- lock : synchronized
- Pay attention to using static variables ( quote ) Use volatile.
analysis :
- ① Before object initialization , Multithreaded call getInstance(), Need to ensure thread safety , I.e. implementation of the 5,6,7,8 That's ok .
- ② After object initialization , Only execute if Judgement and return sentence , That is, only execute the 5,9 That's ok .
② Obvious ratio ① There are many, many cases of implementation , So consider not locking , Increase of efficiency .
② No need to lock , have access to volatile Guaranteed visibility .
namely :
The first 5 That's ok : After initialization , No need to lock , Use volatile Modifying variables , Guaranteed visibility , It can meet thread safety , The code line itself is atomic . It can execute in parallel , Improved efficiency .
The first 6 That's ok : When initialization is not completed , Creating objects requires locking to ensure thread safety .
The first 7 That's ok : Threads that fail to compete for locks , Synchronized code blocks are also executed , It needs to be judged again , Make sure to initialize only once .
The first 9 That's ok : The quotation uses volatile keyword , There is also the establishment of memory barriers , The function of prohibiting instruction reordering (new Decomposed three instructions : Allocate memory space , Initialize object , Assign a value to a variable )
边栏推荐
- Richview RichEdit srichviewedit PageSize page setup and synchronization
- 关于new Set( )还有哪些是你不知道的
- Principle of motion capture system
- C#联合halcon应用——大华相机采集类
- internship:复杂json格式数据编写接口
- 由浅入深学会白盒测试用例设计
- Tensorflow reports an error, could not load dynamic library 'libcudnn so. eight
- [mysql] install mysql5.7
- EURA eurui E1000 series inverter uses PID to realize the relevant parameter setting and wiring of constant pressure water supply function
- 运动捕捉系统原理
猜你喜欢

Richview RichEdit srichviewedit PageSize page setup and synchronization

Niuke programming question -- must brush the string of 101 (brush the question efficiently, draw inferences from one instance)

Powerful, easy-to-use, professional editor / notebook software suitable for programmers / software developers, comprehensive evaluation and comprehensive recommendation

Servlet knowledge points

振弦采集模塊測量振弦傳感器的流程步驟

Hls4ml reports an error the board_ part definition was not found for tul. com. tw:pynq-z2:part0:1.0.

Win11快捷键切换输入法无反应怎么办?快捷键切换输入法没有反应

强大、好用、适合程序员/软件开发者的专业编辑器/笔记软件综合评测和全面推荐

Easycvr accesses the equipment through the national standard gb28181 protocol. What is the reason for the automatic streaming of the equipment?

大厂做狼,小厂做狗?
随机推荐
Anaconda installs the virtual environment to the specified path
全国职业院校技能大赛网络安全“splunk“详细配置
Mo Tianlun salon | Tsinghua qiaojialin: Apache iotdb, originated from Tsinghua, builds an open source ecological road
8K HDR!|为 Chromium 实现 HEVC 硬解 - 原理/实测指南
[untitled]
A quietly rising domestic software, low-key and powerful!
【蓝桥杯Web】2022年第十三届蓝桥杯Web大学组国赛真题解析
Swiftui 4 new features complete toggle and mixed toggle multiple binding components
On the next generation entrance of the metauniverse -- the implementation of brain computer interface
MYSLQ十种锁,一篇文章带你全解析
Exclusive news: Alibaba cloud quietly launched RPA cloud computer and has opened cooperation with many RPA manufacturers
2022/6/8-2022/6/12
STC 32-bit 8051 single chip microcomputer development example tutorial three program compilation setting and download
Tensorflow reports an error, could not load dynamic library 'libcudnn so. eight
Common components of flask
SQL getting started plan-1-select
寫博客文檔
Write blog documents
优质笔记软件综合评测和详细盘点(一) Notion、Obsidian、RemNote、FlowUs

