最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

ScheduledThreadPoolExecutor巨坑解決

 更新時間:2023年02月22日 11:15:10   作者:Code皮皮蝦  
這篇文章主要為大家介紹了使用ScheduledThreadPoolExecutor遇到的巨坑解決示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

概述

最近在做一些優(yōu)化的時候用到了ScheduledThreadPoolExecutor。

雖然知道這個玩意,但是也很久沒用,本著再了解了解的心態(tài),到網(wǎng)上搜索了一下,結果就發(fā)現(xiàn)網(wǎng)上有些博客在說ScheduledThreadPoolExecutor有巨坑!?。?/p>

瞬間,我的興趣就被激起來了,馬上進去學習了一波~

不看不知道,看完后馬上把我的代碼坑給填上了~

下面就當記錄一下吧,順便也帶大家了解了解,大家看完后也趕緊看看自己公司的項目代碼有沒有這種漏洞,有的話趕緊給填上,升級加薪指日可待?。?!

坑是啥?

先看下面案例代碼

public class ScheduledThreadPoolExecutorTest {
  public static ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(2);
  public static AtomicInteger atomicInteger = new AtomicInteger(1);
  public static void main(String[] args) {
    scheduledThreadPoolExecutor.scheduleAtFixedRate(() -> {
      // 模擬業(yè)務邏輯
      int num = atomicInteger.getAndIncrement();
      // 模擬出現(xiàn)異常
      if (num > 3) {
        throw new RuntimeException("定時任務執(zhí)行異常");
      }
      System.out.println("別坑我!");
    }, 0, 1, TimeUnit.SECONDS);
    try {
      TimeUnit.SECONDS.sleep(5);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    scheduledThreadPoolExecutor.shutdown();
  }
}

案例代碼邏輯很簡單,主線程等待5秒后關閉線程池,定時任務執(zhí)行三次后模擬拋出RuntimeException

但是我們看看執(zhí)行結果,只執(zhí)行了三次!

因為某種情況下,定時任務在執(zhí)行第四次時出現(xiàn)異常,從而導致任務調度被取消,不會繼續(xù)執(zhí)行

而且,異常信息也沒有對外拋出!

那么咋解決嘞?try-catch就行了唄~

可以看到執(zhí)行結果,雖然執(zhí)行異常,但是任務卻還是一直在調度~

代碼里使用工具類對Runnable任務包了一層,就是加了try-catch

public class RunnableDecoratorUtil {
   public static Runnable runnableDecorator(Runnable runnable) {
      return () -> {
         try {
            runnable.run();
         } catch (Exception e) {
            e.printStackTrace();
         }
      };
   }
}

okok,總結一下,坑就是: 任務如果拋出異常就不會繼續(xù)調度執(zhí)行了,趕緊去try-catch吧?。?!

大家趕緊去看看自己代碼有沒有這個坑吧,本文到此結束!

開個玩笑~ 光知道有坑哪能不知道為啥坑,接下來就帶大家了解一下坑到底是啥!

怎么坑的?

直接進入scheduleAtFixedRate源碼查看

public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
                                              long initialDelay,
                                              long period,
                                              TimeUnit unit) {
    // 參數(shù)校驗
    if (command == null || unit == null)
        throw new NullPointerException();
    if (period <= 0L)
        throw new IllegalArgumentException();
    // 將任務、執(zhí)行時間、周期等封裝到ScheduledFutureTask內(nèi)
    ScheduledFutureTask<Void> sft =
        new ScheduledFutureTask<Void>(command,
                                      null,
                                      triggerTime(initialDelay, unit),
                                      unit.toNanos(period),
                                      sequencer.getAndIncrement());
    RunnableScheduledFuture<Void> t = decorateTask(command, sft);
    sft.outerTask = t;
    // 延時執(zhí)行
    delayedExecute(t);
    return t;
}

因為我們提交的任務被封裝在ScheduledFutureTask,所以我們直接來看ScheduledFutureTaskrun方法

public void run() {
  // 校驗當前狀態(tài)是否還能執(zhí)行任務,不能執(zhí)行直接cancel取消
  if (!canRunInCurrentRunState(this))
    cancel(false);
  else if (!isPeriodic())
    // 如果不是周期性的,直接調用父類run方法執(zhí)行一次即可
    super.run();
  else if (super.runAndReset()) { // 周期性任務,調用runAndReset運行并重置
    // 設置下一次的執(zhí)行時間
    setNextRunTime();
    // 將任務重新加入隊列,進行調度
    reExecutePeriodic(outerTask);
  }
}
public boolean isPeriodic() {
  return period != 0;
}

我們是周期性任務,所以直接看runAndReset源碼

protected boolean runAndReset() {
    // 檢查任務狀態(tài),cas機制防止并發(fā)執(zhí)行任務
    if (state != NEW ||
        !RUNNER.compareAndSet(this, null, Thread.currentThread()))
        return false;
    // 默認不周期執(zhí)行任務
    boolean ran = false;
    // state為NEW狀態(tài)
    int s = state;
    try {
        Callable<V> c = callable;
        if (c != null && s == NEW) {
            try {
                // 執(zhí)行任務
                c.call();
                // 正常執(zhí)行成功,設置為true代表周期執(zhí)行
                ran = true;
            } catch (Throwable ex) {
                // 但是,如果執(zhí)行異常!則不會將ran = true,所以最終返回false
                setException(ex);
            }
        }
    } finally {
        runner = null;
        // 設置為NEW狀態(tài)
        s = state;
        if (s >= INTERRUPTING)
            handlePossibleCancellationInterrupt(s);
    }
    // 正常執(zhí)行完之后,結果為true,能夠周期執(zhí)行
    // 但如果執(zhí)行異常,ran為false,返回結果為false
    return ran && s == NEW;
}

通過上面源碼,我們可以很清楚的了解到,就是因為任務執(zhí)行異常,且沒有被try-catch,所以導致任務沒有被再次加入到隊列中進行調度。

并且通過文章開頭,我們還能看到任務執(zhí)行異常,但是卻沒有拋出異常信息

那是因為異常被封裝了,只有調用get方法時,才會拋出異常

/** The result to return or exception to throw from get() */
private Object outcome;
private volatile int state;
private static final int NEW          = 0;
private static final int COMPLETING   = 1;
private static final int NORMAL       = 2;
private static final int EXCEPTIONAL  = 3;
private static final int CANCELLED    = 4;
protected void setException(Throwable t) {
    if (STATE.compareAndSet(this, NEW, COMPLETING)) {
        // 將異常信息賦值給outcome
       // outcome既可以為任務執(zhí)行結果也可以為異常信息
        outcome = t;
        // 將state設置為異常狀態(tài),state=3
        STATE.setRelease(this, EXCEPTIONAL); // final state
        finishCompletion();
    }
}
// 調用get方法阻塞獲取結果
public V get() throws InterruptedException, ExecutionException {
  int s = state;
  if (s <= COMPLETING)
    s = awaitDone(false, 0L);
  return report(s);
}
private V report(int s) throws ExecutionException {
  Object x = outcome;
  // 此時s = EXCEPTIONAL = 3
  if (s == NORMAL)
    return (V)x;
  if (s >= CANCELLED)
    throw new CancellationException();
  // 所以會走到這里,對外拋出了任務執(zhí)行的異常
  throw new ExecutionException((Throwable)x);
}

總結

通過上面對源碼的了解,我們了解到,如果周期性任務執(zhí)行出現(xiàn)異常,并且沒有被try-catch,會導致該周期性任務不會再被放入到隊列中進行調度執(zhí)行。

以上就是ScheduledThreadPoolExecutor巨坑解決的詳細內(nèi)容,更多關于ScheduledThreadPoolExecutor坑的資料請關注腳本之家其它相關文章!

相關文章

  • 解讀@Scheduled任務調度/定時任務非分布式

    解讀@Scheduled任務調度/定時任務非分布式

    這篇文章主要介紹了解讀@Scheduled任務調度/定時任務非分布式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • spring?boot自帶的page分頁問題

    spring?boot自帶的page分頁問題

    這篇文章主要介紹了spring?boot自帶的page分頁問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • Java實現(xiàn)全圖背景水印的示例詳解

    Java實現(xiàn)全圖背景水印的示例詳解

    這篇文章主要為大家詳細介紹了如何利用Java實現(xiàn)全圖背景水印的方法,文中的示例代碼講解詳細,具有一定的借鑒價值,需要的可以參考一下
    2023-02-02
  • SpringBoot之@Controller和@RequestMapping的實現(xiàn)原理解讀

    SpringBoot之@Controller和@RequestMapping的實現(xiàn)原理解讀

    這篇文章主要介紹了SpringBoot之@Controller和@RequestMapping的實現(xiàn)原理,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2025-04-04
  • Java環(huán)境中MyBatis與Spring或Spring MVC框架的集成方法

    Java環(huán)境中MyBatis與Spring或Spring MVC框架的集成方法

    和MyBatis類似,Spring或者Spring MVC框架在Web應用程序的運作中同樣主要負責處理數(shù)據(jù)庫事務,這里我們就來看一下Java環(huán)境中MyBatis與Spring或Spring MVC框架的集成方法
    2016-06-06
  • SpringBoot公共模塊配置方式

    SpringBoot公共模塊配置方式

    這篇文章主要介紹了SpringBoot公共模塊配置方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • Spring?cloud網(wǎng)關gateway進行websocket路由轉發(fā)規(guī)則配置過程

    Spring?cloud網(wǎng)關gateway進行websocket路由轉發(fā)規(guī)則配置過程

    這篇文章主要介紹了Spring?cloud網(wǎng)關gateway進行websocket路由轉發(fā)規(guī)則配置過程,文中還通過實例代碼介紹了Spring?Cloud?Gateway--配置路由的方法,需要的朋友可以參考下
    2023-04-04
  • SpringBoot如何對LocalDateTime進行格式化并解析

    SpringBoot如何對LocalDateTime進行格式化并解析

    這篇文章主要介紹了SpringBoot如何對LocalDateTime進行格式化方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • 關于SpringBoot攔截器攔截靜態(tài)資源的問題

    關于SpringBoot攔截器攔截靜態(tài)資源的問題

    這篇文章主要介紹了關于SpringBoot攔截器攔截靜態(tài)資源的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • Java中內(nèi)存問題之OOM詳解

    Java中內(nèi)存問題之OOM詳解

    這篇文章主要介紹了Java中內(nèi)存管理的OOM詳解,OOM,全稱“Out?Of?Memory”,翻譯成中文就是“內(nèi)存用完了”,來源于java.lang.OutOfMemoryError,當JVM因為沒有足夠的內(nèi)存來為對象分配空間并且垃圾回收器也已經(jīng)沒有空間可回收時,就會拋出這個error,需要的朋友可以參考下
    2023-08-08

最新評論

玛多县| 浠水县| 奉新县| 凌源市| 南安市| 黄浦区| 绥化市| 曲周县| 昌都县| 安徽省| 托克托县| 镇赉县| 晋州市| 潼南县| 武鸣县| 赤峰市| 沙坪坝区| 光山县| 徐州市| 牟定县| 年辖:市辖区| 大荔县| 雷山县| 南丹县| 泰州市| 玉树县| 泊头市| 兴山县| 甘洛县| 顺平县| 大安市| 台山市| 皋兰县| 贵德县| 原平市| 保德县| 五大连池市| 乡宁县| 阜新| 苏州市| 苏尼特左旗|