本文主要简述下如何设置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());

这样就大功告成了


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...