ThreadPoolExecutor constructor

/** * The default rejected execution handler */
private static final RejectedExecutionHandler defaultHandler = new AbortPolicy();

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
         Executors.defaultThreadFactory(), defaultHandler);
}
Copy the code
parameter meaning note
corePoolSize Number of core threads, defined when the thread pool is initialized If corePoolSize==maximumPoolSize, threads in the thread pool are not idle and keepAliveTime is no longer useful.
maximumPoolSize Maximum number of threads; Core threads share the thread pool with non-core threads, but core threads are not reclaimed.
keepAliveTime Hold time: if the current number of threads is greater than the number of core threads, the redundant threads that do not perform tasks after waiting keepAliveTime will be reclaimed.
unit KeepAliveTime Unit of keepAliveTime
workQueue Waiting queue
defaultHandler Rejection policies AbortPolicy (default) : Discard directly

Causes of anomalies

When all the threads in the pool are busy, new tasks are submitted to the blocking queue, and when the number of tasks submitted to the blocking queue exceeds the maximum capacity of the queue. The thread pool then refuses to accept the new task and throws an exception.

Four rejection strategies

Name of strategy meaning note
AbortPolicy RejectExecutionException is thrown when the queue is full. You can capture and handle the RejectExecutionException The default policy

Exceptions can be used to discover the concurrency that the system cannot handle
DiscardPolicy Silently discard tasks without throwing exceptions The abnormal state of the system cannot be found and affects services (this can be used for low-importance scenarios with read statistics)
DiscardOldestPolicy Discard the first task in the queue and resubmit the rejected task The “love the new” strategy
CallerRunsPolicy The task is handled by the calling thread (the thread that is currently submitting the task) No exception is thrown and the task is still executed