https://cloud.tencent.com/developer/article/1408125
初學(xué)者很容易看錯(cuò)佩耳,如果沒有看到spring或者JUC源碼的人肯定是不太了解的。
ThreadPoolTaskExecutor是spring core包中的真椿,而ThreadPoolExecutor是JDK中的JUC鹃答。ThreadPoolTaskExecutor是對(duì)ThreadPoolExecutor進(jìn)行了封裝處理。
自己在之前寫多線程代碼的時(shí)候都是這么玩的executor=Executors.newCachedThreadPool();但是有一次在大量數(shù)據(jù)的時(shí)候由于入庫速度遠(yuǎn)大于出庫速度導(dǎo)致內(nèi)存急劇膨脹最后悲劇了重寫代碼突硝,原來spring 早就給我們做好封裝了测摔。
來看一下ThreadPoolExecutor結(jié)構(gòu),祖類都是調(diào)用Executor接口:
再來看一下ThreadPoolTaskExecutor結(jié)構(gòu)解恰,祖類都是調(diào)用Executor接口:
再來看一下源碼:
public class ThreadPoolTaskExecutor extends ExecutorConfigurationSupport implements SchedulingTaskExecutor {
? ? private final Object poolSizeMonitor = new Object();
? ? private int corePoolSize = 1;
? ? private int maxPoolSize = 2147483647;
? ? private int keepAliveSeconds = 60;
? ? private boolean allowCoreThreadTimeOut = false;
? ? private int queueCapacity = 2147483647;
? ? private ThreadPoolExecutor threadPoolExecutor;? //這里就用到了ThreadPoolExecutor
這是ThreadPoolTaskExecutor用來初始化threadPoolExecutor的方法锋八,BlockingQueue是一個(gè)阻塞隊(duì)列,這個(gè)我們先不管护盈。由于ThreadPoolTaskExecutor的實(shí)現(xiàn)方式完全是使用threadPoolExecutor進(jìn)行實(shí)現(xiàn)挟纱,我們需要知道這個(gè)threadPoolExecutor的一些參數(shù)。
public ThreadPoolExecutor(int corePoolSize,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? int maximumPoolSize,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? long keepAliveTime,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? TimeUnit unit,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? BlockingQueue<Runnable> 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.corePoolSize = corePoolSize;
? ? ? ? this.maximumPoolSize = maximumPoolSize;
? ? ? ? this.workQueue = workQueue;
? ? ? ? this.keepAliveTime = unit.toNanos(keepAliveTime);
? ? ? ? this.threadFactory = threadFactory;
? ? ? ? this.handler = handler;
? ? }
? ? int corePoolSize:線程池維護(hù)線程的最小數(shù)量.
int maximumPoolSize:線程池維護(hù)線程的最大數(shù)量.
long keepAliveTime:空閑線程的存活時(shí)間.
TimeUnit unit: 時(shí)間單位,現(xiàn)有納秒,微秒,毫秒,秒枚舉值.
BlockingQueue<Runnable> workQueue:持有等待執(zhí)行的任務(wù)隊(duì)列.
RejectedExecutionHandler handler:
用來拒絕一個(gè)任務(wù)的執(zhí)行腐宋,有兩種情況會(huì)發(fā)生這種情況紊服。
一是在execute方法中若addIfUnderMaximumPoolSize(command)為false,即線程池已經(jīng)飽和胸竞;
二是在execute方法中, 發(fā)現(xiàn)runState!=RUNNING || poolSize == 0,即已經(jīng)shutdown,就調(diào)用ensureQueuedTaskHandled(Runnable command)欺嗤,在該方法中有可能調(diào)用reject。
ThreadPoolExecutor池子的處理流程如下:
1)當(dāng)池子大小小于corePoolSize就新建線程卫枝,并處理請(qǐng)求
2)當(dāng)池子大小等于corePoolSize煎饼,把請(qǐng)求放入workQueue中,池子里的空閑線程就去從workQueue中取任務(wù)并處理
3)當(dāng)workQueue放不下新入的任務(wù)時(shí)剃盾,新建線程入池腺占,并處理請(qǐng)求,如果池子大小撐到了maximumPoolSize就用RejectedExecutionHandler來做拒絕處理
4)另外痒谴,當(dāng)池子的線程數(shù)大于corePoolSize的時(shí)候衰伯,多余的線程會(huì)等待keepAliveTime長的時(shí)間,如果無請(qǐng)求可處理就自行銷毀
其會(huì)優(yōu)先創(chuàng)建? CorePoolSiz 線程积蔚, 當(dāng)繼續(xù)增加線程時(shí)意鲸,先放入Queue中,當(dāng) CorePoolSiz? 和 Queue 都滿的時(shí)候尽爆,就增加創(chuàng)建新線程怎顾,當(dāng)線程達(dá)到MaxPoolSize的時(shí)候,就會(huì)拋出錯(cuò) 誤 org.springframework.core.task.TaskRejectedException
另外MaxPoolSize的設(shè)定如果比系統(tǒng)支持的線程數(shù)還要大時(shí)漱贱,會(huì)拋出java.lang.OutOfMemoryError: unable to create new native thread 異常槐雾。
<!-- 異步線程池 -->
? ? <bean id="threadPool"
? ? ? ? class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
? ? ? ? <!-- 核心線程數(shù),默認(rèn)為1 -->
? ? ? ? <property name="corePoolSize" value="3" />
? ? ? ? <!-- 最大線程數(shù)幅狮,默認(rèn)為Integer.Max_value -->
? ? ? ? <property name="maxPoolSize" value="10" />
? ? ? ? <!-- 隊(duì)列最大長度 >=mainExecutor.maxSize -->
? ? ? ? <property name="queueCapacity" value="25" />
? ? ? ? <!-- 線程池維護(hù)線程所允許的空閑時(shí)間 -->
? ? ? ? <property name="keepAliveSeconds" value="300" />
? ? ? ? <!-- 線程池對(duì)拒絕任務(wù)(無線程可用)的處理策略 ThreadPoolExecutor.CallerRunsPolicy策略 ,調(diào)用者的線程會(huì)執(zhí)行該任務(wù),如果執(zhí)行器已關(guān)閉,則丟棄.? -->
? ? ? ? <property name="rejectedExecutionHandler">
<!-- AbortPolicy:直接拋出java.util.concurrent.RejectedExecutionException異常 -->
<!-- CallerRunsPolicy:若已達(dá)到待處理隊(duì)列長度募强,將由主線程直接處理請(qǐng)求 -->
<!-- DiscardOldestPolicy:拋棄舊的任務(wù)株灸;會(huì)導(dǎo)致被丟棄的任務(wù)無法再次被執(zhí)行 -->
<!-- DiscardPolicy:拋棄當(dāng)前任務(wù);會(huì)導(dǎo)致被丟棄的任務(wù)無法再次被執(zhí)行 -->
? ? ? ? ? ? <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
? ? ? ? </property>
? ? </bean>
Reject策略預(yù)定義有四種:
(1)ThreadPoolExecutor.AbortPolicy策略擎值,是默認(rèn)的策略,處理程序遭到拒絕將拋出運(yùn)行時(shí) RejectedExecutionException慌烧。
(2)ThreadPoolExecutor.CallerRunsPolicy策略 ,調(diào)用者的線程會(huì)執(zhí)行該任務(wù),如果執(zhí)行器已關(guān)閉,則丟棄.
(3)ThreadPoolExecutor.DiscardPolicy策略,不能執(zhí)行的任務(wù)將被丟棄.
(4)ThreadPoolExecutor.DiscardOldestPolicy策略鸠儿,如果執(zhí)行程序尚未關(guān)閉屹蚊,則位于工作隊(duì)列頭部的任務(wù)將被刪除,然后重試執(zhí)行程序(如果再次失敗进每,則重復(fù)此過程).
關(guān)于callable回調(diào)方法(因?yàn)闉殛?duì)列阻塞汹粤,如果到取值某個(gè)執(zhí)行的值會(huì)等待執(zhí)行完成)
? ? ? ? ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
? ? ? ? threadPoolTaskExecutor.setCorePoolSize(5);
? ? ? ? threadPoolTaskExecutor.setMaxPoolSize(50);
? ? ? ? threadPoolTaskExecutor.initialize();
? ? ? ? List<String> paymentSeqNoList = new ArrayList<>();
? ? ? ? for (int i = 0; i < 100; i++) {
? ? ? ? ? ? paymentSeqNoList.add(String.valueOf(i));
? ? ? ? }
? ? ? ? Long startTime = System.currentTimeMillis();
? ? ? ? Map<String, FutureTask<String>> futureMap = new HashMap<String, FutureTask<String>>();
? ? ? ? //線程池提交返回
? ? ? ? for (String paymentSeqNo : paymentSeqNoList) {
? ? ? ? ? ? FutureTask<String> futureTask = new FutureTask<String>(new MyTestCallable(paymentSeqNo));
? ? ? ? ? ? futureMap.put(paymentSeqNo, futureTask);
? ? ? ? ? ? // submit提交執(zhí)行
? ? ? ? ? ? threadPoolTaskExecutor.submit(futureTask);
? ? ? ? }
? ? ? ? Long endTime = System.currentTimeMillis();
? ? ? ? System.out.println("耗時(shí)1:" + (endTime - startTime));
關(guān)于callable回調(diào)值監(jiān)聽是否成功,JDK1.8 也開始支持guava方法了田晚,guava有ListenableFuture 返回優(yōu)化如下:
? Long startTime2 = System.currentTimeMillis();
? ? ? ? ListenableFuture<String> listenableFuture = null;
? ? ? ? for (String paymentSeqNo : paymentSeqNoList) {
? ? ? ? ? ? ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
? ? ? ? ? ? listenableFuture = executorService.submit(new Callable<String>() {
? ? ? ? ? ? ? ? @Override
? ? ? ? ? ? ? ? public String call() throws Exception {
? ? ? ? ? ? ? ? ? ? return "成功";
? ? ? ? ? ? ? ? }
? ? ? ? ? ? });
? ? ? ? }
//監(jiān)聽事件
? ? ? ? Futures.addCallback(listenableFuture, new FutureCallback<String>() {
? ? ? ? ? ? @Override
? ? ? ? ? ? public void onSuccess(String result) {
? ? ? ? ? ? ? ? System.out.println("get listenable future's result with callback " + result);
? ? ? ? ? ? }
? ? ? ? ? ? @Override
? ? ? ? ? ? public void onFailure(Throwable t) {
? ? ? ? ? ? ? ? t.printStackTrace();
? ? ? ? ? ? }
? ? ? ? });
? ? ? ? Long endTime2 = System.currentTimeMillis();
? ? ? ? System.out.println("耗時(shí)2:" + (endTime2 - startTime2));