聊聊TaskExecutor的spring託管

本文主要簡述下如何設置TaskExecutor的Thread.UncaughtExceptionHandler。java

實例

@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方法。spring

配置Thread.UncaughtExceptionHandler

spring默認會給async的線程池配SimpleAsyncUncaughtExceptionHandler,具體見spring-context-4.3.9.RELEASE-sources.jar!/org/springframework/scheduling/annotation/AsyncAnnotationAdvisor.javaasync

不過本身配置的taskExecutor就沒有這個福利了,須要本身配置,以下:ide

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());

這樣就大功告成了ui

相關文章
相關標籤/搜索