Preface
Java thread pool is passedProvidedExecutor frameworkAchieved. The thread pool is mainly composed of
ThreadPoolExecutor
Class support, it provides flexible configuration parameters, allowing developers to adjust the behavior and performance of thread pools according to their needs.
1. Construction method of thread pool
ThreadPoolExecutor
Provides a core construction method that allows specifying key parameters of thread pools:
public ThreadPoolExecutor( int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler )
2. Thread pool parameter analysis
2.1 Core parameters
1. corePoolSize
-
definition:
- The number of core threads, that is, the number of threads that always remain alive in the thread pool.
- Even if the thread pool is idle, the core threads are not recycled (by default).
-
effect:
- When there is a small amount of tasks, the thread pool will prioritize creating core threads to execute tasks.
-
Configuration recommendations:
- Set according to system load and task characteristics.
2. maximumPoolSize
-
definition:
- The maximum number of threads allowed in the thread pool (including core threads).
- When the task queue is full, the thread pool continues to create non-core threads until the maximum number of threads is reached.
-
effect:
- Controls the maximum concurrency capability of the thread pool.
-
Configuration recommendations:
- Set to a suitable value to avoid excessive threads causing system resources to run out.
3. keepAliveTime
-
definition:
- The survival time of a non-core thread (when the thread is idle).
- Non-core threads that have not executed the task after this time will be destroyed.
-
effect:
- Controls the recycling efficiency of thread pool resources.
-
Configuration recommendations:
- For thread pools that require fast response, a shorter survival time can be set.
4. unit
-
definition:
-
keepAliveTime
unit of time. - The value range is
TimeUnit
Enumeration,include:-
(millisecond)
-
(Second)
-
(minute)
-
-
-
effect:
- Standardize the granularity of survival time.
5. workQueue
-
definition:
- A blocking queue that stores tasks waiting to be executed.
- If the number of threads in the thread pool has reached
corePoolSize
, new tasks will be added to the queue and wait.
Common queue types
-
ArrayBlockingQueue:
- Bounded queues, capacity must be specified.
- When the queue is full, the new task will trigger the thread pool expansion.
-
LinkedBlockingQueue:
- Unbounded queues (theoretical capacity is unlimited).
- If unbounded queues are used,
maximumPoolSize
The parameters will be invalid.
-
SynchronousQueue:
- A queue that does not store tasks, each task submitted must be directly handed over to the thread for processing.
- If there are no free threads, the thread pool will immediately create a new thread.
-
PriorityBlockingQueue:
- A queue that supports task sorting.
- Submitted tasks are sorted by priority.
6. threadFactory
-
definition:
- The factory class used to create threads.
-
effect:
- You can customize the thread name, thread priority, whether it is a daemon thread, etc.
-
Example:
ThreadFactory factory = r -> { Thread thread = new Thread(r); ("CustomThread-" + ()); return thread; };
7. handler
-
definition:
- Reject policy, indicating how to handle it when the thread pool cannot accept new tasks.
-
Trigger scene:
- When the task queue is full and the number of threads in the thread pool has reached
maximumPoolSize
hour.
- When the task queue is full and the number of threads in the thread pool has reached
- Common strategies (
RejectedExecutionHandler
Interface implementation):AbortPolicy
(default):- Throw out
RejectedExecutionException
Exception.
CallerRunsPolicy
:- The task is executed directly by the thread that submits the task.
DiscardPolicy
:- Discard the task and do not throw exceptions.
DiscardOldestPolicy
:- Discard the earliest task (queue head task) and try to submit a new task again.
- Throw out
2.2 Thread pool workflow
-
Submit a task:
- Mission passed
execute()
orsubmit()
Methods are submitted to thread pool.
- Mission passed
-
Task processing:
- If the number of threads is not reached
corePoolSize
, create a new thread to handle tasks. - If the number of threads has reached
corePoolSize
, the task entersworkQueue
wait. - If the queue is full and the number of threads is less than
maximumPoolSize
, create a new thread to handle tasks. - If the queue is full and the number of threads reaches
maximumPoolSize
, trigger the rejection policy.
- If the number of threads is not reached
-
Thread Recycling:
- Exceed
keepAliveTime
Unused non-core threads will be destroyed.
- Exceed
3. Common thread pool implementation
Java provides some convenient methods for thread pooling:
3.1 Executors Factory Method
-
newFixedThreadPool(int nThreads)
:- Fixed-size thread pool.
- The number of core threads and the maximum number of threads is equal, and an unbounded queue is used.
ExecutorService fixedPool = (5);
-
newCachedThreadPool()
:- Cacheable thread pool.
- The thread pool size is unlimited, and threads are recycled if they are idle for more than 60 seconds.
ExecutorService cachedPool = ();
-
newSingleThreadExecutor()
:- Single threaded thread pool.
- Ensure that tasks are executed in the order of submission.
ExecutorService singleThreadPool = ();
-
newScheduledThreadPool(int corePoolSize)
:- A thread pool that supports timing and periodic tasks.
ScheduledExecutorService scheduledPool = (5);
3.2 Custom thread pool
passThreadPoolExecutor
Construct a custom thread pool:
ExecutorService customPool = new ThreadPoolExecutor( 2, // Number of core threads 4, // Maximum number of threads 60, // Non-core thread survival time , // Unit of survival time new ArrayBlockingQueue<>(10), // Blocking queue (), // Default thread factory new () // Reject policy);
4. Optimization suggestions for parameter configuration
4.1 Number of core threads (corePoolSize)
-
I/O intensive tasks:
- The number of core threads is usually set to2 * CPU core number。
- Tasks need to frequently wait for external resources (such as disks, networks), and the number of threads can be increased appropriately.
-
CPU intensive tasks:
- The number of core threads is set toCPU core number + 1。
- Too many threads will increase the overhead of context switching.
4.2 Maximum number of threads (maximumPoolSize)
- The size of the thread pool should be within the allowable range of the system resources to avoid excessive threads causing resource exhaustion.
4.3 Queue type (workQueue)
-
Short task queue:
- use
SynchronousQueue
, does not store tasks, suitable for high throughput scenarios.
- use
-
Limited task queue:
- use
ArrayBlockingQueue
Limit the queue length to prevent memory overflow.
- use
-
Priority queue:
- use
PriorityBlockingQueue
, suitable for scenarios where task sorting is required.
- use
4.4 Denied policy (handler)
-
High reliability:
- use
CallerRunsPolicy
, fall back the task to the calling thread to execute.
- use
-
Low priority tasks:
- use
DiscardPolicy
orDiscardOldestPolicy
Discard the task.
- use
5. Sample code
import .*; public class ThreadPoolExample { public static void main(String[] args) { ExecutorService threadPool = new ThreadPoolExecutor( 2, // Number of core threads 4, // MaximumNumber of threads 60L, // Idle thread survival time , // Time unit new LinkedBlockingQueue<>(10), // Blocking queue (), // Thread factory new () // Reject policy ); for (int i = 0; i < 20; i++) { (() -> { (().getName() + " is executing"); }); } (); } }
6. Summary
parameter | effect | Optimization suggestions |
---|---|---|
corePoolSize |
Number of core threads, number of threads that always survive | Setting reasonably according to task type and system resources |
maximumPoolSize |
Maximum number of threads, limiting the maximum concurrency of thread pool | Avoid setting too high to prevent resource exhaustion |
keepAliveTime |
Survival time of non-core threads | Adjust according to response needs |
workQueue |
Waiting for task queues to store unprocessed tasks | Use the appropriate queue type |
handler |
Reject policy, determine behavior when a task cannot be processed | Choose the right strategy based on task importance |
By rationally configuring thread pool parameters, the performance and resource utilization of multi-threaded programs can be significantly improved.
This is the end of this article about the detailed explanation of Java thread pool parameters. For more detailed explanation of Java thread pool parameters, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!