当前位置:网站首页>A brief analysis of the four process pools
A brief analysis of the four process pools
2022-07-27 13:30:00 【Fried cat】
A brief analysis of the four process pools
List of articles
1、FixedThreadPool
1.1、 Parameter analysis
Fixed-length thread pool , First, let's take a look at the parameters of the construction method created .
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
characteristic :
- The number of core threads is equal to that of non core threads , therefore Only core threads exist , There are no non core threads .
- If you don't actively set , The life cycle of the core thread is the same as that of the thread pool .
- Unbounded blocking queue
LinkedBlockingQueue.
1.2、 Use scenarios
Because there are only core threads , And the maximum length of the thread is fixed , So it applies to :
- The number of tasks is relatively fixed
- The process is long
2、ScheduledThreadPool
2.1、 Parameter analysis
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}
characteristic :
- The number of core threads is
corePoolSize, The number of non core threads is unlimited . - If you don't actively set , The life cycle of the core thread is the same as that of the thread pool ;, If there are no tasks in the queue Non core threads will be recycled immediately .
- Adopted delay queue
DelayedWorkQueue.
2.2、 Application scenarios
It is suitable for performing scheduled tasks and repetitive tasks with specific fixed cycles
3、CachedThreadPool
3.1、 Parameter analysis
Buffer thread pool .
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
characteristic :
- Only non core threads exist , The core thread is 0, Infinite non core threads .
- The idle time of non core threads is
60s, exceed 60s It's going to be recycled . - Synchronous blocking queue
SynchronousQueue, The characteristic length of this queue is 1 , Only when there are idle threads will they join the queue , Otherwise, directly create a new non core thread to execute the task .
3.2、 Application scenarios
Applicable to many tasks , Tasks with short process time .
4、SingleThreadExecutor
4.1、 Parameter analysis
Singleton thread pool
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
characteristic :
- The number of core threads and non core threads is 1.
- The thread life cycle is the same as the thread pool .
- Unbounded blocking queue LinkedBlockingQueue
4.2、 Applicable scenario
Apply to Scenarios in which tasks are executed sequentially .
5、 Queue selection
Before execution enters the queue , First, be familiar with the execution process of the process pool :
If the number of worker threads is less than corePoolSize( Core thread ) The number of , At this time, the task will not join the team , Instead, create a new thread directly to execute the task , Then go to the queue to get new tasks to execute .
If the number of worker threads is greater than or equal to corePoolSize At this time, the team entry operation will be carried out , Whether to create threads in the future depends on maximumPoolSize( Maximum thread ) And whether there are worker threads .
5.1、 Unbounded queue
Unbounded queue is characterized by unlimited queue size (Integer.MAX_VALUE), The commonly used unbounded queue is LinkedBlockingQueue. Aforementioned SingleThreadExecutor、FixedThreadPool The two thread pools are the blocking queues . When using this queue , Note that the queue size is unlimited , Avoid memory overflow caused by storing too much data .
5.2、 Bounded queues
Corresponding to unbounded queue , The queue size is limited , There are two common types , One is to follow FIFO A queue of principles, such as ArrayBlockingQueue, The other is the priority queue, such as PriorityBlockingQueue.PriorityBlockingQueue The priority in is determined by the priority of the task Comparator decision .
When using bounded queue, the queue size and thread pool size should match each other , When the thread pool is small and the bounded queue is large, the memory consumption can be reduced , Reduce cpu Usage and context switching , However, it may limit the system throughput .
5.3、 Synchronous handover queue
The use of the queue process pool is , Tasks don't have to wait , Only when there are idle threads can tasks be queued , Otherwise, create a new thread directly , The corresponding is CachedThreadPool Thread pool . So using this queue may create a large number of threads , Pay attention to use .
6、 Refusal strategy
6.1、AbortPolicy
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
Directly throw exception strategy , The user can directly catch the exception , Further processing , For example, you can add tasks to the thread pool again , Or just give up .
6.2、CallerRunsPolicy
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
r.run();
}
}
You can see the strategy , There is no exception thrown , I didn't give up , It's a direct call to run Method , Instead of calling in the thread pool , So this strategy will block the execution of the main thread , Let the main thread execute the task .
6.3、DiscardPolicy
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
}
Do nothing , Give up the task directly .
6.4、DiscardOldestPolicy
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
1、 Queue up a task in the queue .
e.getQueue().poll();
e.execute(r);
}
}
Such as code , First, the header element in the blocking queue is dequeued and discarded , Try submitting the task again . If the queue is blocked at this time, use PriorityBlockingQueue Priority queue , Will cause the highest priority task to be abandoned , Therefore, it is not recommended to use this strategy with priority queue .
边栏推荐
猜你喜欢
![51: Chapter 5: develop admin management services: 4: develop [add admin account, interface]; (only [user name + password, method]; [@t...] annotation controls transactions; when setting cookies, do yo](/img/6f/4f93eca1d923a58b2ef4b1947538be.png)
51: Chapter 5: develop admin management services: 4: develop [add admin account, interface]; (only [user name + password, method]; [@t...] annotation controls transactions; when setting cookies, do yo

Getting started for beginners: build your own blog with WordPress

MTK6765编译环境搭建

51:第五章:开发admin管理服务:4:开发【新增admin账号,接口】;(只开发了【用户名+密码的,方式】;【@T…】注解控制事务;设置cookie时,是否需要使用URLEncoder去编码;)

Preliminary discussion on NetGen and Gmsh mesh generation of any multiple sub models of CAD based on osg+occ

eBPF/Ftrace

SCI论文写作

双料第一!

v-text

18. Text processing tool -grep
随机推荐
Flinksql synchronizes data from Oracle to Doris, with a total of more than 50 fields and more than 30 million entries in Oracle tables
clear
leetcode——83,24;机器学习——神经网络
以科技传递温度,vivo亮相数字中国建设峰会
高度塌陷最终解决方案(无副作用)
二分法查询数组中的值
7.26模拟赛总结
面试官常问:如何手撸一个“消息队列”和“延迟消息队列”?
Jesd204b debugging notes (practical version)
最新版泛域名证书申请
Antd's tool function getprefixcls gets the public prefix
Insert sort, positive order, reverse order
Firefox 103 release, faster and more secure
How about the strength of database HTAP
3D laser slam:aloam---ceres optimization part and code analysis
Icon Font
【基础知识】~ 集成电路设计流程,以及各阶段所使用的EDA工具
滑环使用如何固定
592. Fraction addition and subtraction: introduction to expression calculation
Dichotomy queries values in an array