当前位置:网站首页>Talk about connection pools and threads
Talk about connection pools and threads
2022-07-27 02:49:00 【Love coriander】
One 、 Connection pool
1、 What is connection pooling ? Why do we need it ?
Connection pooling allows multiple clients to use cached connection objects , These objects can connect to the database , They are shared 、 Reusable .
open / Closing the database connection is expensive , Connection pooling technology allows us to maintain connection objects in the connection pool , This can improve the performance of executing commands in the database . Multiple client requests can reuse the same connection object , Every time a client request is received ,
Will search the connection pool , See if there are idle connection objects . without , Either all client requests are queued , Or create a new connection object in the pool ( It depends on how many connections exist in the pool and how many connections the configuration supports ).
Once a request has used the connection object , This object will be put back into the pool , It will then be reassigned to queued requests ( Which request is assigned depends on what scheduling algorithm is used ).
Because most requests use existing connection objects , Therefore, connection pooling technology greatly reduces the time waiting to create a database connection , This reduces the average connection time .
2、 How to use connection pool ?
Connection pooling is common in network-based enterprise applications , The application server is responsible for creating connection objects 、 Add them to the connection pool , Assign the connection object to the request , Recycle the used connection objects , Put them back into the connection pool .
When a web application creates a database connection , The application server will take the connection object out of the pool , And when it is closed after use , The application server is responsible for putting the used connection objects back into the pool .
PS: You can also use JDBC 1.0/JDBC 2.0 API To get the physical connection (physical connnection), But this is very rare , Because the database only needs to be connected once , No connection pool is required .
3、 How many connections can the connection pool handle ? Who created / Release the connection ?
The maximum number of connections that can be configured 、 Minimum connections 、 Maximum number of idle connections , All these parameters can be configured by the server administrator . When the server starts , A fixed number of connected objects ( Minimum number of connections configured ) Be created , And add it to the connection pool .
When the client requests to consume all the connection objects , Any new request will create a new connection object , They are added to the connection pool and then assigned to the new request , Until the maximum number of connections is set .
The server will always check the number of idle connection objects , When it is detected that the number of idle connections exceeds the set value , The server will close idle connections , Then they will be recycled .
4、 Traditional connection pooling vs Manageable connection pool
Connection pooling is an open concept , Any application can use this concept , And manage it in the way you want . The connection pool concept refers to creating 、 management 、 Maintain connection objects .
But when the scale of the application increases , Without a robust connection pooling mechanism , Managing connections will become increasingly difficult .
therefore , Build a robust 、 Manageable connection pooling is necessary .
Two 、 Threads & Thread pool , Connect & Connection pool
Threads : The smallest unit of program execution flow , An entity in the process , A relatively independent 、 A schedulable execution unit , It is the basic unit independently scheduled and dispatched by the system ;
Multithreading technology , It means that multiple threads can be created in a process to “ meanwhile ” Handle multiple transactions ;
Thread pool : It can be understood as buffer , Due to the frequent creation and destruction of threads, there will be a certain cost , You can pre create , But not destroyed immediately , Serve others in a shared way , This can provide efficiency , Furthermore, it can control the wireless expansion of threads .
Connect : Refers to the connection between one point and another ;
Connection pool : It has the same beauty as thread pool , But connection pooling can be implemented based on Multithreading , It can also be achieved through multiple processes , It may also be single instance .
for instance :
Socket As a service , You can listen to multiple client connections at the same time , Then its implementation principle is a bit like “ Connection pool ”; Each customer sends data to the server at the same time through multiple ports , It can be considered as multithreading ,
And the server may have been established n Threads to wait for simultaneous processing / Analyze the data sent by the client , There can be a “ Thread pool ”.
3、 ... and 、 Several states of threads
Threads under certain conditions , The state will change . Threads have the following states :
1、 New state (New): A new thread object is created .
2、 Ready state (Runnable): After the thread object is created , Other threads called the object's start() Method . The thread in this state is in “ Runnable thread pool ” in , Become operational , Just wait to get CPU Right to use ,
That is, the process in the ready state is divided into CPU outside , All other resources needed for operation have been obtained .
3、 Running state (Running): The ready state is obtained by the thread CPU, Execute program code .
4、 Blocked state (Blocked): Blocking is when the thread gives up for some reason CPU Right to use , Stop running temporarily . Until the thread is ready , To have a chance to go to run state .
There are three types of obstruction :
①. Waiting for a jam : The running thread executes wait() Method , This thread will release all the resources occupied ,JVM Will put the thread into “ Waiting pool ” in . After entering this state , Can't wake up automatically ,
You have to rely on other threads to call notify() or notifyAll() Method can be awakened ,
②. Synchronous blocking : When a running thread acquires a synchronized lock for an object , If the synchronization lock is held by another thread , be JVM Will put the thread into “ Lock pool ” in .
③. Other blockages : The running thread executes sleep() or join() Method , Or send out I/O When asked ,JVM It puts the thread in a blocking state . When sleep() Status timeout 、join() Wait for the thread to terminate or timeout ,
perhaps I/O When it's done , Thread is ready again .
5、 Death state (Dead): The thread executes or exits due to an exception run() Method , The thread ends its life cycle .
The state transition diagram of thread change is as follows :

PS: Get the lock mark of the object , That is, you get the object ( A critical region ) Permission to use . That is, the thread obtains the resources required for running , Get into “ Ready state ”, Just get CPU, Can run .
Because when calling wait() after , The thread will release what it owns “ Lock sign ”, Therefore, the thread can enter the ready state only when it obtains resources here .
The following is an explanation :
①. There are two ways to implement threads , One is inheritance Thread class , Two is the realization. Runnable Interface , But anyway , When we new After you get this object , The thread is in its initial state ;
②. When the object calls start() Method , It's ready ;
③. When ready , When the object is selected by the operating system , get CPU The time slice will be running ;
④. After entering the running state, the situation is more complicated ;
(1)run() Method or main() After the method is over , The thread is terminated ;
(2) When a thread calls its own sleep() Method or other thread join() Method , Process surrender CPU, Then it will enter the blocking state ( This state stops the current thread , But it doesn't release the resources it occupies ,
That is to call sleep() After the function , The thread will not release its “ Lock sign ”.). When sleep() End or join() After the end , The thread enters a runnable state , Continue to wait for OS Distribute CPU Time slice ;
Typically ,sleep() Used to wait for a resource to be ready ; After the test found that the conditions were not met , Let the thread block for a while and retest , Until the conditions are met .
(3) The thread called yield() Method , It means to give up what you currently get CPU Time slice , Back to ready , At this time, it is in the same competitive state with other processes ,OS It's possible that the process will then be run again ;
call yield() The effect is equivalent to the scheduler thinking that the thread has executed enough time slices to need to go to another thread .yield() Just bring the current thread back to the executable state ,
So execute yield() It is possible that the thread in the executable state will be executed immediately .
(4) When a thread has just entered a runnable state ( Be careful , It's not running yet ), It was found that the resource to be called was deleted synchroniza( Sync ), Cannot get lock tag , Will immediately enter the lock pool state , Waiting to get the lock tag
( At this time, there may be other threads in the lock pool waiting to get the lock mark , Now they're in a queue , First come, first served ), Once the thread gets the lock tag , It goes to the ready state , wait for OS Distribute CPU Time slice .
(5)suspend() and resume() Method : The two methods are used together ,suspend() Put the thread in a blocked state , And it doesn't automatically recover , It must correspond to resume() Called , To get the thread back to the executable state .
Typically ,suspend() and resume() Used to wait for another thread to produce results : The test found that the results have not yet been produced , Let threads block , After another thread produces the result , call resume() Restore it .
(6)wait() and notify() Method : When a thread calls wait() Method will enter the waiting queue ( Entering this state will release all the resources occupied , Unlike the blocking state ), After entering this state , Can't wake up automatically ,
You have to rely on other threads to call notify() or notifyAll() Method can be awakened ( because notify() Just wake up a thread , But we can't determine which thread is waking up , Maybe the thread we need to wake up can't be woken up ,
So in actual use , Commonly used notifyAll() Method , Wake up thread ), When the thread is awakened, it will enter the lock pool , Waiting to get the lock tag .
wait() Put the thread in a blocked state , It comes in two forms :
A method that allows you to specify in ms Time in units as a parameter , The other has no parameters . The former corresponds to notify() When it is called or exceeds the specified time, the thread re enters the executable state, that is, the ready state , The latter must correspond to notify() Called .
When calling wait() after , The thread will release what it owns “ Lock sign ”, So that other objects in the thread are synchronized Data can be used by other threads .
waite() and notify() Because it's going to affect the object “ Lock sign ” To operate , So they have to be in synchronized Function or synchronizedblock Call in the .
If in non-synchronized Function or non-synchronizedblock Call in the , Although it can be compiled and passed , But it happens at run time IllegalMonitorStateException It's abnormal .
Now I invite you to join our software testing learning exchange group :【746506216】, remarks “ The group of ”, We can discuss communication software testing together , Learn software testing together 、 Interview and other aspects of software testing , There will also be free live classes , Gain more testing skills , Let's advance together Python automated testing / Test Development , On the road to high pay .
Friends who like software testing , If my blog helps you 、 If you like my blog content , please “ give the thumbs-up ” “ Comment on ” “ Collection ” One Key triple connection !
边栏推荐
- 手动从0搭建ABP框架-ABP官方完整解决方案和手动搭建简化解决方案实践
- Redis distributed lock implemented by annotation
- [untitled]
- 数据库读写分离和分库分表
- [draw rectangular coordinate system in C language]
- Functions of libraries and Archives
- 【Code】剑指offer 04二维数组中的查找
- Little sister's notes: how do I learn simple source code to expand my horizons
- How many holes have you stepped on in BigDecimal?
- php+swoole
猜你喜欢

Ubuntu基于docker的mysql主从数据库配置

测试人需要的数据库知识:MySQL常用语法

面试突击68:为什么 TCP 需要 3 次握手?

Make static routing accessible to the whole network through ENSP

pyqt5使用pyqtgraph画动态散点图

Uni app wechat applet search keywords are displayed in red

贪心——376. 摆动序列

Okaleido tiger logged into binance NFT on July 27, and has achieved good results in the first round

【Redis】快速入门

uni-app 微信小程序搜索关键字标红显示
随机推荐
膜拜,阿里内部都在强推的321页互联网创业核心技术pdf,真的跪了
进程的调度
项目时区问题解决
The latest multi-threaded & highly concurrent learning materials, interview confidence
[brother Yang takes you to play with the linear table (I) - sequence table]
C语言程序的编译(预处理)下
Greenplum【部署 08】数据库小版本升级流程及问题处理 Error: open-source-greenplum-db-6 conflicts with
Okaleido Tiger 7.27日登录Binance NFT,首轮已获不俗成绩
com.fasterxml.jackson.databind.exc.InvalidDefinitionException
在腾讯测试岗干了5年,7月无情被辞,想给还在划水的兄弟提个醒.....
贪心——376. 摆动序列
小姐姐笔记:我是如何学习简单源码拓展视野的
OSPF routing information protocol topology experiment
最新多线程&高并发学习资料,面试心里有底气
Graduated and entered HW, from test engineer to project manager. Now I earn millions in goose factory every year. My suggestions to you
【无标题】
什么是进程?
小程序怎样助力智能家居生态新模式
Shell 分析日志文件命令全面总结
Talk about the metrics of automated testing