優點:重寫ThreadPoolExecutor afterExecute方法 - 任何缺點?的鉤方法
beforeExecute(Thread, Runnable)
和afterExecute(Runnable, Throwable)
beforeExecute(Thread, Runnable
)和afterExecute(Runnable, Throwable)
方法之前和每個任務的執行之後被調用。這些可以用來操縱執行環境;例如,重新初始化ThreadLocals,收集統計信息或添加日誌條目
我正在使用自定義ThreadPoolExecutor
來處理未捕獲的異常。我可以在Runnable
和Callable
中添加try{} catch{}
塊,但假設您不能強制開發人員在相關的Runnable
和Callable任務中添加這些塊。
這CustomThreadPoolExecutor
,覆蓋afterExecute
()方法在ThreadPoolExecutor
如下(I已分配變量b的值爲零以模擬算術異常。
import java.util.concurrent.*;
import java.util.*;
class CustomThreadPoolExecutor extends ThreadPoolExecutor {
public CustomThreadPoolExecutor() {
super(1,10,60,TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(1000));
}
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if (t == null && r instanceof Future<?>) {
try {
Object result = ((Future<?>) r).get();
System.out.println(result);
} catch (CancellationException ce) {
t = ce;
} catch (ExecutionException ee) {
t = ee.getCause();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // ignore/reset
}
}
if (t != null)
t.printStackTrace();
}
}
public class CustomThreadPoolExecutorDemo{
public static void main(String args[]){
System.out.println("creating service");
//ExecutorService service = Executors.newFixedThreadPool(10);
CustomThreadPoolExecutor service = new CustomThreadPoolExecutor();
service.submit(new Runnable(){
public void run(){
int a=4, b = 0;
System.out.println("a and b="+a+":"+b);
System.out.println("a/b:"+(a/b));
System.out.println("Thread Name in Runnable after divide by zero:"+Thread.currentThread().getName());
}
});
service.shutdown();
}
}
由於submit()
在框架隱藏例外,我已重寫afterExecute()
方法捕獲異常。
在這種方法中,我添加了阻塞調用下面的語句
Object result = ((Future<?>) r).get();
目前我有10個線程,隊列容量爲1000.假設我的Runnable
需要5秒鐘才能完成。
通過覆蓋afterExecute
()方法,我是否會招致任何性能開銷或任何與此方法的利弊?
看猜測性能不是一件好事,只是基準有和沒有覆蓋的代碼,並檢查是否有相關的變化。 http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – Jack