使用ScheduledThreadPoolExecutor踩過最痛的坑
概述
最近項目上反饋某個重要的定時任務突然不執(zhí)行了,很頭疼,開發(fā)環(huán)境和測試環(huán)境都沒有出現(xiàn)過這個問題。
定時任務采用的是 ScheduledThreadPoolExecutor
,后來一看代碼發(fā)現(xiàn)踩了一個大坑....
還原"大坑"
這個坑就是如果 ScheduledThreadPoolExecutor
中執(zhí)行的任務出錯拋出異常后,不僅不會打印異常堆棧信息,同時還會取消后面的調度
直接看例子
@Test public void testException() throws InterruptedException { // 創(chuàng)建1個線程的調度任務線程池 ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); // 創(chuàng)建一個任務 Runnable runnable = new Runnable() { volatile int num = 0; @Override public void run() { num ++; // 模擬執(zhí)行報錯 if(num > 5) { throw new RuntimeException("執(zhí)行錯誤"); } log.info("exec num: [{}].....", num); } }; // 每隔1秒鐘執(zhí)行一次任務 scheduledExecutorService.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS); Thread.sleep(10000); }
運行結果:
- 只執(zhí)行了5次后,就不打印,不執(zhí)行了,因為報錯了
- 任務報錯,也沒有打印一次堆棧,更導致調度任務取消,后果十分嚴重。
解決方案
解決方法也非常簡單,只要通過try catch捕獲異常即可。
運行結果:
看到不僅打印了異常堆棧,而且也會進行周期性的調度。
更推薦的做法
更好的建議可以在自己的項目中封裝一個包裝類,要求所有的調度都提交通過我們統(tǒng)一的包裝類, 如下代碼:
@Slf4j public class RunnableWrapper implements Runnable { // 實際要執(zhí)行的線程任務 private Runnable task; // 線程任務被創(chuàng)建出來的時間 private long createTime; // 線程任務被線程池運行的開始時間 private long startTime; // 線程任務被線程池運行的結束時間 private long endTime; // 線程信息 private String taskInfo; private boolean showWaitLog; /** * 執(zhí)行間隔時間多久,打印日志 */ private long durMs = 1000L; // 當這個任務被創(chuàng)建出來的時候,就會設置他的創(chuàng)建時間 // 但是接下來有可能這個任務提交到線程池后,會進入線程池的隊列排隊 public RunnableWrapper(Runnable task, String taskInfo) { this.task = task; this.taskInfo = taskInfo; this.createTime = System.currentTimeMillis(); } public void setShowWaitLog(boolean showWaitLog) { this.showWaitLog = showWaitLog; } public void setDurMs(long durMs) { this.durMs = durMs; } // 當任務在線程池排隊的時候,這個run方法是不會被運行的 // 但是當任務結束了排隊,得到線程池運行機會的時候,這個方法會被調用 // 此時就可以設置線程任務的開始運行時間 @Override public void run() { this.startTime = System.currentTimeMillis(); // 此處可以通過調用監(jiān)控系統(tǒng)的API,實現(xiàn)監(jiān)控指標上報 // 用線程任務的startTime-createTime,其實就是任務排隊時間 // 這邊打印日志輸出,也可以輸出到監(jiān)控系統(tǒng)中 if(showWaitLog) { log.info("任務信息: [{}], 任務排隊時間: [{}]ms", taskInfo, startTime - createTime); } // 接著可以調用包裝的實際任務的run方法 try { task.run(); } catch (Exception e) { log.error("run task error", e); throw e; } // 任務運行完畢以后,會設置任務運行結束的時間 this.endTime = System.currentTimeMillis(); // 此處可以通過調用監(jiān)控系統(tǒng)的API,實現(xiàn)監(jiān)控指標上報 // 用線程任務的endTime - startTime,其實就是任務運行時間 // 這邊打印任務執(zhí)行時間,也可以輸出到監(jiān)控系統(tǒng)中 if(endTime - startTime > durMs) { log.info("任務信息: [{}], 任務執(zhí)行時間: [{}]ms", taskInfo, endTime - startTime); } } }
使用:
我們還可以在包裝類里面封裝各種監(jiān)控行為,如本例打印日志執(zhí)行時間等。
原理探究
那大家有沒有想過為什么任務出錯會導致異常無法打印,甚至調度都取消了呢?讓我們從源碼出發(fā),一探究竟。
下面是調度任務的入口方法
// ScheduledThreadPoolExecutor#scheduleAtFixedRate public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { if (command == null || unit == null) throw new NullPointerException(); if (period <= 0) throw new IllegalArgumentException(); // 將執(zhí)行任務和參數(shù)包裝成ScheduledFutureTask對象 ScheduledFutureTask<Void> sft = new ScheduledFutureTask<Void>(command, null, triggerTime(initialDelay, unit), unit.toNanos(period)); RunnableScheduledFuture<Void> t = decorateTask(command, sft); sft.outerTask = t; // 延遲執(zhí)行 delayedExecute(t); return t; } 復制代碼
這個方法主要做了兩個事情
- 將執(zhí)行任務和參數(shù)包裝成ScheduledFutureTask對象
- 調用
delayedExecute
方法延遲執(zhí)行任務
延遲或周期性任務的主要執(zhí)行方法, 主要是將任務丟到隊列中,后續(xù)由工作線程獲取執(zhí)行。
// ScheduledThreadPoolExecutor#delayedExecute private void delayedExecute(RunnableScheduledFuture<?> task) { if (isShutdown()) reject(task); else { // 將任務丟到阻塞隊列中 super.getQueue().add(task); if (isShutdown() && !canRunInCurrentRunState(task.isPeriodic()) && remove(task)) task.cancel(false); else // 開啟工作線程,去執(zhí)行任務,或者從隊列中獲取任務執(zhí)行 ensurePrestart(); } }
現(xiàn)在任務已經(jīng)在隊列中了,我們看下任務執(zhí)行的內(nèi)容是什么,還記得前面的包裝對象 ScheduledFutureTask
類,它的實現(xiàn)類是 ScheduledFutureTask
,繼承了Runnable類。
// ScheduledFutureTask#run方法 public void run() { // 是不是周期性任務 boolean periodic = isPeriodic(); if (!canRunInCurrentRunState(periodic)) cancel(false); // 不是周期性任務的話, 直接調用一次下面的run else if (!periodic) ScheduledFutureTask.super.run(); // 如果是周期性任務,則調用runAndReset方法,如果返回true,繼續(xù)執(zhí)行 else if (ScheduledFutureTask.super.runAndReset()) { // 設置下次調度時間 setNextRunTime(); // 重新執(zhí)行調度任務 reExecutePeriodic(outerTask); } }
這里的關鍵就是看 ScheduledFutureTask.super.runAndReset()
方法是否返回true,如果是true的話繼續(xù)調度。
runAndReset方法也很簡單,關鍵就是看報異常如何處理。
// FutureTask#runAndReset protected boolean runAndReset() { if (state != NEW || !UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread())) return false; // 是否繼續(xù)下次調度,默認false boolean ran = false; int s = state; try { Callable<V> c = callable; if (c != null && s == NEW) { try { // 執(zhí)行任務 c.call(); // 執(zhí)行成功的話,設置為true ran = true; // 異常處理,關鍵點 } catch (Throwable ex) { // 不會修改ran的值,最終是false,同時也不打印異常堆棧 setException(ex); } } } finally { // runner must be non-null until state is settled to // prevent concurrent calls to run() runner = null; // state must be re-read after nulling runner to prevent // leaked interrupts s = state; if (s >= INTERRUPTING) handlePossibleCancellationInterrupt(s); } // 返回結果 return ran && s == NEW; }
- 關鍵點ran變量,最終返回是不是下次繼續(xù)調度執(zhí)行
- 如果拋出異常的話,可以看到不會修改ran為true。
總結
Java的ScheduledThreadPoolExecutor定時任務線程池所調度的任務中如果拋出了異常,并且異常沒有捕獲直接拋到框架中,會導致ScheduledThreadPoolExecutor定時任務不調度了。
這個結論希望大家一定要記住,不然非??樱P鍵是有時候測試環(huán)境、開發(fā)環(huán)境還無法復現(xiàn),有一定的隨機性,真的到了生產(chǎn)就完蛋了。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
關于這些知識點,我們不僅要知其然,還要知其所以然,這樣才會記憶深刻,不然很容易遺忘。
- 詳解Java ScheduledThreadPoolExecutor的踩坑與解決方法
- Java調度線程池ScheduledThreadPoolExecutor不執(zhí)行問題分析
- ScheduledThreadPoolExecutor巨坑解決
- java高并發(fā)ScheduledThreadPoolExecutor類深度解析
- java高并發(fā)ScheduledThreadPoolExecutor與Timer區(qū)別
- java 定時器線程池(ScheduledThreadPoolExecutor)的實現(xiàn)
- Java自帶定時任務ScheduledThreadPoolExecutor實現(xiàn)定時器和延時加載功能
相關文章
Java easyexcel導出報內(nèi)存溢出的問題解決
在Java開發(fā)時,使用EasyExcel處理大數(shù)據(jù)量導出可能遇到內(nèi)存溢出問題,本文深入分析了內(nèi)存溢出的原因,并提出了優(yōu)化策略,感興趣的可以了解一下2024-10-10IDEA下因Lombok插件產(chǎn)生的Library source does not match the bytecode報
這篇文章主要介紹了IDEA下因Lombok插件產(chǎn)生的Library source does not match the bytecode報錯問題及解決方法,親測試過好用,需要的朋友可以參考下2020-04-04使用FeignClient調用遠程服務時整合本地的實現(xiàn)方法
這篇文章主要介紹了使用FeignClient調用遠程服務時整合本地的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03