先看下包结构
@SPI("fixed")
public interface ThreadPool {
/**
//使用 URL.threadpool 属性加载对应的实现
*/
@Adaptive({"threadpool"})
Executor getExecutor(URL url);
}
复制代码
FixedThreadPool
public class FixedThreadPool implements ThreadPool {
@Override
public Executor getExecutor(URL url) {
//线程名
String name = url.getParameter("threadname", "Dubbo");
// 线程数
int threads = url.getParameter("threads", 200);
// 队列数
int queues = url.getParameter("queues", 0);
// 创建执行器
return new ThreadPoolExecutor(threads, threads, 0, TimeUnit.MILLISECONDS,
queues == 0 ? new SynchronousQueue<Runnable>() :
(queues < 0 ? new LinkedBlockingQueue<Runnable>()
: new LinkedBlockingQueue<Runnable>(queues)),
new NamedInternalThreadFactory(name, true), new AbortPolicyWithReport(name, url));
}
//根据不同的队列数,使用不同的队列实现
//queues == 0 , SynchronousQueue
//queues < 0 , LinkedBlockingQueue
//queues > 0 ,带队列数的 LinkedBlockingQueue
复制代码
CachedThreadPool
缓存线程池,空闲一定时长,自动删除,需要时重建
*/
public class CachedThreadPool implements ThreadPool {
@Override
public Executor getExecutor(URL url) {
// 线程池名
String name = url.getParameter("threadname", "Dubbo");
//核心线程数
int cores = url.getParameter("corethreads", 0);
// 最大线程数
int threads = url.getParameter("threads", Integer.MAX_VALUE);
// 队列数
int queues = url.getParameter("queues", 0);
// 线程存活时长
int alive = url.getParameter("alive", 60 * 1000);
return new ThreadPoolExecutor(cores, threads, alive, TimeUnit.MILLISECONDS,
queues == 0 ? new SynchronousQueue<Runnable>() :
(queues < 0 ? new LinkedBlockingQueue<Runnable>()
: new LinkedBlockingQueue<Runnable>(queues)),
new NamedInternalThreadFactory(name, true), new AbortPolicyWithReport(name, url));
}
}
复制代码
//LimitedThreadPool
可伸缩线程池,但池中的线程数只会增长不会收缩。只增长不收缩的目的是为了避免收缩时突然来了大流量引起的性能问题。
*/
public class LimitedThreadPool implements ThreadPool {
@Override
public Executor getExecutor(URL url) {
// 线程名
String name = url.getParameter(Constants.THREAD_NAME_KEY, Constants.DEFAULT_THREAD_NAME);
// 核心线程数
int cores = url.getParameter(Constants.CORE_THREADS_KEY, Constants.DEFAULT_CORE_THREADS);
// 最大线程数
int threads = url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS);
// 队列数
int queues = url.getParameter(Constants.QUEUES_KEY, Constants.DEFAULT_QUEUES);
//和 CachedThreadPool 实现是基本一致的,差异点在 alive == Integer.MAX_VALUE ,空闲时间无限大,即不会自动删除。
return new ThreadPoolExecutor(cores, threads, Long.MAX_VALUE, TimeUnit.MILLISECONDS,
queues == 0 ? new SynchronousQueue<Runnable>() :
(queues < 0 ? new LinkedBlockingQueue<Runnable>()
: new LinkedBlockingQueue<Runnable>(queues)),
new NamedInternalThreadFactory(name, true), new AbortPolicyWithReport(name, url));
}
}
复制代码