java after方法_java – 覆盖ThreadPoolExecutor afterExecute方法 – 任何缺点?

钩子方法的优点:

beforeExecute(Thread,Runnable)和afterExecute(Runnable,Throwable)

beforeExecute(Thread, Runnable) and afterExecute(Runnable, Throwable) methods that are called before and after execution of each task. These can be used to manipulate the execution environment; for example, reinitializing ThreadLocals, gathering statistics, or adding log entries

我正在使用Custom ThreadPoolExecutor来处理未捕获的异常.我可以在Runnable和Callable中添加try {} catch {}块,但假设您不能强迫开发人员在相关的Runnable和Callable任务中添加这些块.

这个CustomThreadPoolExecutor,如下所示覆盖ThreadPoolExecutor中的afterExecute()方法(我已将变量b值赋值为零以模拟算术异常.

import java.util.concurrent.*;

import java.util.*;

class CustomThreadPoolExecutor extends ThreadPoolExecutor {

public CustomThreadPoolExecutor() {

super(1,10,60,TimeUnit.SECONDS,new ArrayBlockingQueue(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()方法,我是否会产生任何性能开销或这种方法的任何缺点?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值