天天看點

面試官:線程池中線程抛了異常,該如何處理?

1. 模拟線程池抛異常

在實際開發中,我們常常會用到線程池,但任務一旦送出到線程池之後,如果發生異常之後,怎麼處理?怎麼擷取到異常資訊?在了解這個問題之前,可以先看一下 線程池的源碼解析,從連結中我們知道了線程池的送出方式:submit和execute的差別,接下來分别使用他們執行帶有異常的任務!看結果是怎麼樣的!

我們先用僞代碼模拟一下線程池抛異常的場景:

public class ThreadPoolException {
    public static void main(String[] args) {

        //建立一個線程池
        ExecutorService executorService= Executors.newFixedThreadPool(1);

        //當線程池抛出異常後 submit無提示,其他線程繼續執行
        executorService.submit(new task());

        //當線程池抛出異常後 execute抛出異常,其他線程繼續執行新任務
        executorService.execute(new task());
    }
}

//任務類
class task implements  Runnable{

    @Override
    public void run() {
        System.out.println("進入了task方法!!!");
        int i=1/0;

    }
}      

運作結果:

面試官:線程池中線程抛了異常,該如何處理?

可以看到:submit不列印異常資訊,而execute則會列印異常資訊!,submit的方式不列印異常資訊,顯然在生産中,是不可行的,因為我們無法保證線程中的任務永不異常,而如果使用submit的方式出現了異常,直接如上寫法,我們将無法擷取到異常資訊,做出對應的判斷和處理,是以下一步需要知道如何擷取線程池抛出的異常!

​submit()​

​​想要擷取異常資訊就必須使用​

​get()​

​方法!!

//當線程池抛出異常後 submit無提示,其他線程繼續執行
Future<?> submit = executorService.submit(new task());
submit.get();      

submit列印異常資訊如下:

面試官:線程池中線程抛了異常,該如何處理?

2. 如何擷取和處理異常

方案一:使用 ​

​try -catch​

public class ThreadPoolException {
    public static void main(String[] args) {
        
        //建立一個線程池
        ExecutorService executorService = Executors.newFixedThreadPool(1);

        //當線程池抛出異常後 submit無提示,其他線程繼續執行
        executorService.submit(new task());

        //當線程池抛出異常後 execute抛出異常,其他線程繼續執行新任務
        executorService.execute(new task());
    }
}
// 任務類
class task implements Runnable {
    @Override
    public void run() {
        try {
            System.out.println("進入了task方法!!!");
            int i = 1 / 0;
        } catch (Exception e) {
            System.out.println("使用了try -catch 捕獲異常" + e);
        }
    }
}      

列印結果:

面試官:線程池中線程抛了異常,該如何處理?

可以看到 submit 和 execute都清晰易懂的捕獲到了異常,可以知道我們的任務出現了問題,而不是消失的無影無蹤。

方案二:使用​

​Thread.setDefaultUncaughtExceptionHandler​

​方法捕獲異常

方案一中,每一個任務都要加一個​

​try-catch​

​​ 實在是太麻煩了,而且代碼也不好看,那麼這樣想的話,可以用​

​Thread.setDefaultUncaughtExceptionHandler​

​方法捕獲異常

面試官:線程池中線程抛了異常,該如何處理?

​UncaughtExceptionHandler​

​ 是Thread類一個内部類,也是一個函數式接口。

内部的​

​uncaughtException​

​是一個處理線程内發生的異常的方法,參數為線程對象t和異常對象e。

面試官:線程池中線程抛了異常,該如何處理?

應用線上程池中如下所示:重寫它的線程工廠方法,線上程工廠建立線程的時候,都賦予​

​UncaughtExceptionHandler​

​處理器對象。

public class ThreadPoolException {
    public static void main(String[] args) throws InterruptedException {


        //1.實作一個自己的線程池工廠
        ThreadFactory factory = (Runnable r) -> {
            //建立一個線程
            Thread t = new Thread(r);
            //給建立的線程設定UncaughtExceptionHandler對象 裡面實作異常的預設邏輯
            t.setDefaultUncaughtExceptionHandler((Thread thread1, Throwable e) -> {
                System.out.println("線程工廠設定的exceptionHandler" + e.getMessage());
            });
            return t;
        };

        //2.建立一個自己定義的線程池,使用自己定義的線程工廠
        ExecutorService executorService = new ThreadPoolExecutor(
                1,
                1,
                0,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue(10),
                factory);

        // submit無提示
        executorService.submit(new task());

        Thread.sleep(1000);
        System.out.println("==================為檢驗列印結果,1秒後執行execute方法");

        // execute 方法被線程工廠factory 的UncaughtExceptionHandler捕捉到異常
        executorService.execute(new task());


    }


}

class task implements Runnable {
    @Override
    public void run() {
        System.out.println("進入了task方法!!!");
        int i = 1 / 0;
    }
}      

列印結果如下:

面試官:線程池中線程抛了異常,該如何處理?

根據列印結果我們看到,execute方法被線程工廠factory中設定的 ​

​UncaughtExceptionHandler​

​​捕捉到異常,而submit方法卻沒有任何反應!說明​

​UncaughtExceptionHandler​

​在submit中并沒有被調用。這是為什麼呢?

在日常使用中,我們知道,execute和submit最大的差別就是execute沒有傳回值,submit有傳回值。submit傳回的是一個future ,可以通過這個future取到線程執行的結果或者異常資訊。

Future<?> submit = executorService.submit(new task());
//列印異常結果
  System.out.println(submit.get());      
面試官:線程池中線程抛了異常,該如何處理?

從結果看出:submit并不是丢失了異常,使用​

​future.get()​

​​還是有異常列印的!!那為什麼線程工廠factory 的​

​UncaughtExceptionHandler​

​​沒有列印異常呢?猜測是submit方法内部已經捕獲了異常, 隻是沒有列印出來,也因為異常已經被捕獲,是以jvm也就不會去調用Thread的​

​UncaughtExceptionHandler​

​去處理異常。

接下來,驗證猜想:

首先看一下submit和execute的源碼:

execute方法的源碼在這部落格中寫的很詳細,點選檢視execute源碼,在此就不再啰嗦了

submit源碼在底層還是調用的execute方法,隻不過多一層Future封裝,并傳回了這個Future,這也解釋了為什麼submit會有傳回值

//submit()方法
 public <T> Future<T> submit(Callable<T> task) {
     if (task == null) throw new NullPointerException();
     
     //execute内部執行這個對象内部的邏輯,然後将結果或者異常 set到這個ftask裡面
     RunnableFuture<T> ftask = newTaskFor(task); 
     // 執行execute方法
     execute(ftask); 
     //傳回這個ftask
     return ftask;
 }      

可以看到submit也是調用的execute,在execute方法中,我們的任務被送出到了​

​addWorker(command, true)​

​ ,然後為每一個任務建立一個Worker去處理這個線程,這個Worker也是一個線程,執行任務時調用的就是Worker的run方法!run方法内部又調用了runworker方法!如下所示:

public void run() {
        runWorker(this);
 }
     
final void runWorker(Worker w) {
     Thread wt = Thread.currentThread();
     Runnable task = w.firstTask;
     w.firstTask = null;
     w.unlock(); // allow interrupts
     boolean completedAbruptly = true;
     try {
      //這裡就是線程可以重用的原因,循環+條件判斷,不斷從隊列中取任務        
      //還有一個問題就是非核心線程的逾時删除是怎麼解決的
      //主要就是getTask方法()見下文③
         while (task != null || (task = getTask()) != null) {
             w.lock();
             if ((runStateAtLeast(ctl.get(), STOP) ||
                  (Thread.interrupted() &&
                   runStateAtLeast(ctl.get(), STOP))) &&
                 !wt.isInterrupted())
                 wt.interrupt();
             try {
                 beforeExecute(wt, task);
                 Throwable thrown = null;
                 try {
                  //執行線程
                     task.run();
                     //異常處理
                 } catch (RuntimeException x) {
                     thrown = x; throw x;
                 } catch (Error x) {
                     thrown = x; throw x;
                 } catch (Throwable x) {
                     thrown = x; throw new Error(x);
                 } finally {
                  //execute的方式可以重寫此方法處理異常
                     afterExecute(task, thrown);
                 }
             } finally {
                 task = null;
                 w.completedTasks++;
                 w.unlock();
             }
         }
         //出現異常時completedAbruptly不會被修改為false
         completedAbruptly = false;
     } finally {
      //如果如果completedAbruptly值為true,則出現異常,則添加新的Worker處理後邊的線程
         processWorkerExit(w, completedAbruptly);
     }
 }      

核心就在 ​

​task.run(); ​

​這個方法裡面了, 期間如果發生異常會被抛出。

  • 如果用execute送出的任務,會被封裝成了一個runable任務,然後進去 再被封裝成一個worker,最後在worker的run方法裡面調用runWoker方法,​

    ​runWoker​

    ​方法裡面執行任務任務,如果任務出現異常,用​

    ​try-catch​

    ​捕獲異常往外面抛,我們在最外層使用​

    ​try-catch​

    ​捕獲到了 ​

    ​runWoker​

    ​方法中抛出的異常。是以我們在execute中看到了我們的任務的異常資訊。
  • 那麼為什麼submit沒有異常資訊呢?因為submit是将任務封裝成了一個​

    ​futureTask​

    ​ ,然後這個​

    ​futureTask​

    ​被封裝成worker,在woker的run方法裡面,最終調用的是​

    ​futureTask​

    ​的run方法, 猜測裡面是直接吞掉了異常,并沒有抛出異常,是以在worker的​

    ​runWorker​

    ​方法裡面無法捕獲到異常。

下面來看一下​

​futureTask​

​​的run方法,果不其然,在try-catch中吞掉了異常,将異常放到了 ​

​setException(ex);​

​裡面

public void run() {
     if (state != NEW ||
         !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                      null, Thread.currentThread()))
         return;
     try {
         Callable<V> c = callable;
         if (c != null && state == NEW) {
             V result;
             boolean ran;
             try {
                 result = c.call();
                 ran = true;
             } catch (Throwable ex) {
                 result = null;
                 ran = false;
                 //在此方法中設定了異常資訊
                 setException(ex);
             }
             if (ran)
                 set(result);
         }
         //省略下文
 。。。。。。      

​setException(ex)​

​​方法如下:将異常對象賦予​

​outcome​

protected void setException(Throwable t) {
       if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
        //将異常對象賦予outcome,記住這個outcome,
           outcome = t;
           UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
           finishCompletion();
       }
   }      

将異常對象賦予​

​outcome​

​​有什麼用呢?這個​

​outcome​

​​是什麼呢?當我們使用submit傳回Future對象,并使用​

​Future.get()​

​時, 會調用内部的report方法!

public V get() throws InterruptedException, ExecutionException {
    int s = state;
    if (s <= COMPLETING)
        s = awaitDone(false, 0L);
    //注意這個方法
    return report(s);
}      

reoport裡面實際上傳回的是outcome ,剛好之前的異常就set到了這個outcome裡面

private V report(int s) throws ExecutionException {
 //設定`outcome`
    Object x = outcome;
    if (s == NORMAL)
     //傳回`outcome`
        return (V)x;
    if (s >= CANCELLED)
        throw new CancellationException();
    throw new ExecutionException((Throwable)x);
}      

是以,在用submit送出的時候,runable對象被封裝成了future ,future 裡面的 run方法在處理異常時, ​

​try-catch​

​​了所有的異常,通過​

​setException(ex);​

​​方法設定到了變量outcome裡面, 可以通過​

​future.get​

​擷取到outcome。面試寶典:https://www.yoodb.com

是以在submit送出的時候,裡面發生了異常, 是不會有任何抛出資訊的。而通過​

​future.get()​

​​可以擷取到submit抛出的異常!在submit裡面,除了從傳回結果裡面取到異常之外, 沒有其他方法。是以,在不需要傳回結果的情況下,最好用execute ,這樣就算沒有寫​

​try-catch​

​,疏漏了異常捕捉,也不至于丢掉異常資訊。

方案三:重寫afterExecute進行異常處理

通過上述源碼分析,在excute的方法裡面,可以通過重寫​

​afterExecute​

​​進行異常處理,但是注意!這個也隻适用于excute送出(submit的方式比較麻煩,下面說),因為submit的​

​task.run​

​​裡面把異常吞了,根本不會跑出來異常,是以也不會有異常進入到a​

​fterExecute​

​裡面。

在​

​runWorker​

​​裡面,調用task.run之後,會調用線程池的 ​

​afterExecute(task, thrown)​

​ 方法。

final void runWorker(Worker w) {
//目前線程
        Thread wt = Thread.currentThread();
        //我們的送出的任務
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts
        boolean completedAbruptly = true;
        try {
            while (task != null || (task = getTask()) != null) {
                w.lock();
                if ((runStateAtLeast(ctl.get(), STOP) ||
                     (Thread.interrupted() &&
                      runStateAtLeast(ctl.get(), STOP))) &&
                    !wt.isInterrupted())
                    wt.interrupt();
                try {
                    beforeExecute(wt, task);
                    Throwable thrown = null;
                    try {
                    //直接就調用了task的run方法 
                        task.run(); //如果是futuretask的run,裡面是吞掉了異常,不會有異常抛出,
                       // 是以Throwable thrown = null;  也不會進入到catch裡面
                    } catch (RuntimeException x) {
                        thrown = x; throw x;
                    } catch (Error x) {
                        thrown = x; throw x;
                    } catch (Throwable x) {
                        thrown = x; throw new Error(x);
                    } finally {
                    //調用線程池的afterExecute方法 傳入了task和異常
                        afterExecute(task, thrown);
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }
            completedAbruptly = false;
        } finally {
            processWorkerExit(w, completedAbruptly);
        }
    }      

重寫​

​afterExecute​

​處理execute送出的異常

public class ThreadPoolException3 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {


        //1.建立一個自己定義的線程池
        ExecutorService executorService = new ThreadPoolExecutor(
                2,
                3,
                0,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue(10)
        ) {
            //重寫afterExecute方法
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                System.out.println("afterExecute裡面擷取到異常資訊,處理異常" + t.getMessage());
            }
        };
        
        //當線程池抛出異常後 execute
        executorService.execute(new task());
    }
}

class task3 implements Runnable {
    @Override
    public void run() {
        System.out.println("進入了task方法!!!");
        int i = 1 / 0;
    }
}      

執行結果:我們可以在​

​afterExecute​

​方法内部對異常進行處理。

面試官:線程池中線程抛了異常,該如何處理?

如果要用這個​

​afterExecute​

​​處理submit送出的異常, 要額外處理。判斷​

​Throwable​

​​是否是​

​FutureTask​

​,如果是代表是submit送出的異常,代碼如下:

public class ThreadPoolException3 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {


        //1.建立一個自己定義的線程池
        ExecutorService executorService = new ThreadPoolExecutor(
                2,
                3,
                0,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue(10)
        ) {
            //重寫afterExecute方法
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                //這個是excute送出的時候
                if (t != null) {
                    System.out.println("afterExecute裡面擷取到excute送出的異常資訊,處理異常" + t.getMessage());
                }
                //如果r的實際類型是FutureTask 那麼是submit送出的,是以可以在裡面get到異常
                if (r instanceof FutureTask) {
                    try {
                        Future<?> future = (Future<?>) r;
                        //get擷取異常
                        future.get();

                    } catch (Exception e) {
                        System.out.println("afterExecute裡面擷取到submit送出的異常資訊,處理異常" + e);
                    }
                }
            }
        };
        //當線程池抛出異常後 execute
        executorService.execute(new task());
        
        //當線程池抛出異常後 submit
        executorService.submit(new task());
    }
}

class task3 implements Runnable {
    @Override
    public void run() {
        System.out.println("進入了task方法!!!");
        int i = 1 / 0;
    }
}      

處理結果如下:

面試官:線程池中線程抛了異常,該如何處理?