Talk about the spring hosting of TaskExecutor.

  java

Order

This article mainly briefly describes how to set up TaskExecutor’s Thread. UncaughtException Handler.

Example

    @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;
    }

The advantage of using spring Managed TaskExecutor is that you can make some preparation or cleaning actions when the spring container is started or destroyed. It can be specified by initMethod and destroyMethod respectively.
DestroyMethod looks for the public’s parameterless method named close or shutdown by default. There is no configuration here. The default call is the shutdown method of ThreadPoolTaskScheduler.

Configure thread.uncaughtexceptionhandler

Spring will assign SimpleSync’s thread pool with SimpleSynccunCaughtexceptionHandler by default. For details, see Spring-Context-4.3.9.Release-Sources.jar! /org/springframework/scheduling/annotation/AsyncAnnotationAdvisor.java

However, the taskExecutor configured by itself does not have this benefit and needs to be configured by itself, as follows:

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

This is the end of the story.