当前位置:网站首页>[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 model
The 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 loaded
So 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 safe
OfHe 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 efficiency
A 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 used
And 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 safe
This 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 slow
Of .
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 position
2、 double if determine
3、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 )
边栏推荐
- 1592 example 1 King (sgu223 loj10170 luogu1896 increase + / provincial election -) violent thinking pressure DP 01 Backpack
- fastDFS入门
- Gaussdb (for MySQL):partial result cache, which accelerates the operator by caching intermediate results
- Interview questions shared in today's group
- Summary of SQL aggregate query method for yyds dry goods inventory
- Error in installing sharp
- EURA eurui E1000 series inverter uses PID to realize the relevant parameter setting and wiring of constant pressure water supply function
- Simple but modern server dashboard dashdot
- How to connect the two nodes of the flow chart
- After adding cocoapods successfully, the header file cannot be imported or an error is reported in not found file
猜你喜欢
Flask 常用组件
简单但现代的服务器仪表板Dashdot
一个悄然崛起的国产软件,低调又强大!
目标检测——Yolo系列
Procédure de mesure du capteur d'accord vibrant par le module d'acquisition d'accord vibrant
Myslq ten kinds of locks, an article will take you to fully analyze
Win11暂停更新点不了怎么办?Win11暂停更新是灰色的如何解决?
Detailed configuration of network security "Splunk" in national vocational college skills competition
Error in installing sharp
GaussDB(for MySQL) :Partial Result Cache,通过缓存中间结果对算子进行加速
随机推荐
写博客文档
Using qeventloop to realize synchronous waiting for the return of slot function
On the next generation entrance of the metauniverse -- the implementation of brain computer interface
Data analysts sound tall? Understand these points before you decide whether to transform
Procédure de mesure du capteur d'accord vibrant par le module d'acquisition d'accord vibrant
Optimization of the problem that the request flow fails to terminate during page switching of easycvr cluster video Plaza
走进如心小镇,数智化变革连接“未来社区”
牛客编程题--必刷101之字符串(高效刷题,举一反三)
300题线性代数 第四讲 线性方程组
Problems encountered in installing MySQL in docker Ubuntu container
Bind this of the current scope for callback functions in other cases such as timers and delayers
如何用OpenMesh创建一个四棱锥
Review the collection container again
What if the win11 shortcut key switching input method doesn't respond? Shortcut key switching input method does not respond
网上开户是安全的吗?新手可以开炒股账户吗。
Hls4ml/vivado HLS error reporting solution
C # joint Halcon application - Dahua camera acquisition class
PowerDesigner design name and comment replacement
docker ubuntu容器中安装mysql遇到的问题
STC 32-bit 8051 single chip microcomputer development example tutorial three program compilation setting and download