为什么需要调用ThreadPoolExecutor构造方法去创建线程池,因为阿里巴巴开发手册如是说:
【ThreadPoolExecutor构造方法的七个参数和拒绝策略详解】
文章图片
那我们先了解下ThreadPoolExecutor构造方法的七个参数代表什么。
ThreadPoolExecutor类的源码如下:
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters.
*
* @param corePoolSize the number of threads to keep in the pool, even
*if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @param maximumPoolSize the maximum number of threads to allow in the
*pool
* @param keepAliveTime when the number of threads is greater than
*the core, this is the maximum time that excess idle threads
*will wait for new tasks before terminating.
* @param unit the time unit for the {@code keepAliveTime} argument
* @param workQueue the queue to use for holding tasks before they are
*executed.This queue will hold only the {@code Runnable}
*tasks submitted by the {@code execute} method.
* @param threadFactory the factory to use when the executor
*creates a new thread
* @param handler the handler to use when execution is blocked
*because the thread bounds and queue capacities are reached
* @throws IllegalArgumentException if one of the following holds:
*{@code corePoolSize < 0}
*{@code keepAliveTime < 0}
*{@code maximumPoolSize <= 0}
*{@code maximumPoolSize < corePoolSize}
* @throws NullPointerException if {@code workQueue}
*or {@code threadFactory} or {@code handler} is null
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
其实源码中方法上的注释已经很清楚了(阅读源码注释是个很好的习惯),我们这里简单翻译下:
corePoolSize: 核心线程数,即一直保留在线程池当中的线程数量,即使没有任务需要处理。
maximumPoolSize: 最大线程数,当前线程池中允许创建的最大线程数。
keepAliveTime:存活时间,大于核心线程数的线程等待新任务的最长时间,这个时间内没有新任务需要处理,则销毁这个线程
unit:存活时间的单位,TumeUnit类,有NANOSECONDS,MICROSECONDS,MILLISECONDS,SECONDS,MINUTES,HOURS,DAYS选项
workQueue:任务队列。用于在执行任务之前保存任务的队列。 此队列将仅保存由 execute 方法提交的 Runnable 任务。当有新任务来时,会先判断当前任务队列是否已经满员,如果未满,加入队列等候执行,如果已满则开启新的线程。如果线程数达到最大线程数,则执行拒绝策略(第七个参数)
threadFactory:执行器创建新线程时使用的工厂,默认DefaultThreadFactory
handler:拒绝策略RejectedExecutionHandler。默认AbortPolicy
我们可以看到实现RejectedExecutionHandler的实现类有四个:
文章图片
见名知意我们简单理解下:
AbortPolicy:中止策略,针对满员后的新任务直接抛出RejectedExecutionException异常
CallerRunsPolicy: 由当前线程次所在的线程去执行被拒绝的新任务。
DiscardPolicy:丢弃策略,空方法什么都不干,等于直接忽略了新任务,不执行但是也不抛出异常。
DiscardOldestPolicy:丢弃最早的策略。当任务被拒绝是,会抛弃任务队列中最旧的任务也就是最先加入队列的,再把这个新任务添加进去。e.getQueue().poll();
/* Predefined RejectedExecutionHandlers *//**
* A handler for rejected tasks that runs the rejected task
* directly in the calling thread of the {@code execute} method,
* unless the executor has been shut down, in which case the task
* is discarded.
*/
public static class CallerRunsPolicy implements RejectedExecutionHandler {
/**
* Creates a {@code CallerRunsPolicy}.
*/
public CallerRunsPolicy() { }/**
* Executes task r in the caller's thread, unless the executor
* has been shut down, in which case the task is discarded.
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
r.run();
}
}
}/**
* A handler for rejected tasks that throws a
* {@code RejectedExecutionException}.
*/
public static class AbortPolicy implements RejectedExecutionHandler {
/**
* Creates an {@code AbortPolicy}.
*/
public AbortPolicy() { }/**
* Always throws RejectedExecutionException.
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
* @throws RejectedExecutionException always
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}/**
* A handler for rejected tasks that silently discards the
* rejected task.
*/
public static class DiscardPolicy implements RejectedExecutionHandler {
/**
* Creates a {@code DiscardPolicy}.
*/
public DiscardPolicy() { }/**
* Does nothing, which has the effect of discarding task r.
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
}
}/**
* A handler for rejected tasks that discards the oldest unhandled
* request and then retries {@code execute}, unless the executor
* is shut down, in which case the task is discarded.
*/
public static class DiscardOldestPolicy implements RejectedExecutionHandler {
/**
* Creates a {@code DiscardOldestPolicy} for the given executor.
*/
public DiscardOldestPolicy() { }/**
* Obtains and ignores the next task that the executor
* would otherwise execute, if one is immediately available,
* and then retries execution of task r, unless the executor
* is shut down, in which case task r is instead discarded.
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
if (!e.isShutdown()) {
e.getQueue().poll();
e.execute(r);
}
}
}
了解了上述七个参数后,我们再看看阿里云规范中不提倡的线程池对象:
FixedThreadPool
/**
* FixedThreadPool是核心线程和最大线程一样,但是队列没指定容量,默认是MAX_VALUE。所有可以一直创建新任务,导致OOM
*/
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue());
}
public LinkedBlockingQueue() {
this(Integer.MAX_VALUE);
}
SingleThreadExecutor
/**
* SingleThreadExecutor是单个线程,但是队列没指定容量,默认是MAX_VALUE。所有可以一直创建新任务,导致OOM
*/
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue()));
}
CachedThreadPool
/**
* CachedThreadPool最大线程是是MAX_VALUE,默认的队列是SynchronousQueue,是阻塞的。所以有新任务来就会创建新的线程,导致OOM
*/
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue());
}
ScheduledThreadPool
/**
* CachedThreadPool最大线程是是MAX_VALUE,队列是DelayedWorkQueue默认长度为16。所以可以一直创建新的线程,导致OOM
*/
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}