2017-04-20 88 views
1

的Javadoc的ThreadPoolExecutor定義(https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html#afterExecute(java.lang.Runnable,%20java.lang.Throwable)如果發生異常,ThreadPoolExecutor :: afterExecute是否會返回runnable?

protected void afterExecute(Runnable r, Throwable t) 

將在初始運行的被傳遞給函數在出現異常的情況下?

+0

你是什麼意思與「可運行返回」? – Jesper

+0

@Jesper reffrased –

+0

是的,在Runnable引發異常的情況下,'Runnable'會傳遞給'afterExecute'; API文檔解釋了這一點。爲什麼你懷疑它?你也可以嘗試一下並自己去看看(創建一個擴展'ThreadPoolExecutor'的類,覆蓋'afterExecute'方法,讓它執行一個'Runnable',引發一個異常並檢查你的'afterExecute'是否按預期調用) 。 – Jesper

回答

1

它被返回。這是很容易檢查 - 考慮基於文檔代碼:

public class MainApp { 

    public static void main(String[] args) { 
     testme(); 
    } 

    public static void testme() { 
     ThreadPoolExecutor myown = new ExtendedExecutor(2,4,10, TimeUnit.DAYS.SECONDS, new ArrayBlockingQueue<Runnable>(2)); 

     myown.execute(() -> { 
       throw new RuntimeException("Something went wrong"); 
    //   System.out.println("Hey there"); 
     } 
    ); 
} 


static class ExtendedExecutor extends ThreadPoolExecutor { 

    public ExtendedExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { 
     super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); 
    } 

    protected void afterExecute(Runnable r, Throwable t) { 
     super.afterExecute(r, t); 
     if (t == null && r instanceof Future<?>) { 
      try { 
       Object result = ((Future<?>) r).get(); 
      } catch (CancellationException ce) { 
       t = ce; 
      } catch (ExecutionException ee) { 
       t = ee.getCause(); 
      } catch (InterruptedException ie) { 
       Thread.currentThread().interrupt(); // ignore/reset 
      } 
     } 
     if (t != null) { 
      System.out.println("We've got error"); 
      System.out.println(r==null?"null":"not null"); 
     } 
    } 
} 
相關問題