聊聊TaskExecutor的spring托管

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

这样就大功告成了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值