合作机构:阿里云 / 腾讯云 / 亚马逊云 / DreamHost / NameSilo / INWX / GODADDY / 百度统计
封装自定义线程池类是为了在线程执行完毕后,我们检查是否存在异常,如果存在异常,日志打印详细异常信息,这样可以可以帮助我们及时发现和解决问题。
JDK 默认提供的定时调度线程池类是
ScheduledThreadPoolExecutor,我们只需要继承它并重写它的 afterExecute 方法,添加异常日志打印的逻辑。
public class MyScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
private Logger log = LoggerFactory.getLogger(MyScheduledThreadPoolExecutor.class);
public MyScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory factory) {
super(corePoolSize, factory);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
// 打印异常信息
this.printException(r, t);
}
public void printException(Runnable r, Throwable t) {
// 判断 r 是 Future 实例并且已经完成执行的情况下,获取它的执行结果,并检查是否有异常抛出
if (t == null && r instanceof Future<?>) {
try {
Future<?> future = (Future<?>) r;
if (future.isDone()) {
future.get();
}
} catch (CancellationException ce) {
t = ce;
} catch (ExecutionException ee) {
t = ee.getCause();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
if (t != null) {
log.error(t.getMessage(), t);
}
}
}
TOP