序
本文主要简述下如何设置TaskExecutor的Thread.UncaughtExceptionHandler。
实例
@Bean
protected ThreadPoolTaskScheduler taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(50);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("demo-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.initialize();
return executor;
}
使用spring托管TaskExecutor的好处就是可以在spring容器启动或销毁的时候做些准备或清理动作。分别可以用initMethod及destroyMethod来指定。
destroyMethod默认寻找public的命名为close或者shutdown的无参方法,这里没有配置,默认调用的是ThreadPoolTaskScheduler的shutdown方法。
配置Thread.UncaughtExceptionHandler
spring默认会给async的线程池配SimpleAsyncUncaughtExceptionHandler,具体见spring-context-4.3.9.RELEASE-sources.jar!/org/springframework/scheduling/annotation/AsyncAnnotationAdvisor.java
不过自己配置的taskExecutor就没有这个福利了,需要自己配置,如下:
final Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
//do what you want
}
};
ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder();
threadFactoryBuilder.setNameFormat("demo-%d");
threadFactoryBuilder.setUncaughtExceptionHandler(uncaughtExceptionHandler);
executor.setThreadFactory(threadFactoryBuilder.build());
这样就大功告成了
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。