Recovering Asynchronous ThreadPoolTaskexecutor After Server Crash / Shutdown

I have a Spring wait controller that calls an asynchronous method using the Spring @Async methodology and immediately returns the http (Accepted) code to the client. (An asynchronous job is heavy and can lead to a timeout). So, at the end of the asynchronous task, I send an email to the client, telling him the status of his request.

Everything works fine, but I ask myself, what can I do if the server / jvm crashes or closes it? My client will receive code 202 and will never receive a status email address.

Is there a way to synchronize (in real time) ThreadPoolTaskExecutor in a database or even in a file so that the server recovers at startup without managing it independently with complex rules and evolution status?

Here is my executor configuration

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(8);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("asyncTaskExecutor-");
        executor.setAwaitTerminationSeconds(120);
        executor.setKeepAliveSeconds(30);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }

}

Controller starting an asynchronous task

@RequestMapping(value = "/testAsync", method = RequestMethod.GET)
public void testAsync() throws InterruptedException{
    businessService.doHeavyThings();
}

Asynchronous Method:

@Async
public void doHeavyThings() throws InterruptedException {

    LOGGER.error("Start doHeavyThings with configured executor - " + Thread.currentThread().getName() + " at " + new Date());
    Thread.sleep(5000L);
    LOGGER.error("Stop doHeavyThings with configured executor - " + Thread.currentThread().getName() + " at " + new Date());
}

}

thank

+4
source share
1 answer

To shut down the web server, the application life cycle in the java web application will not display ServletContextListener . If you provide an implementation of ServletContextListener, you can put your "what has already been processed" logic in the method contextDestroyed.

- contextInitialized.

Spring .

0

Source: https://habr.com/ru/post/1663329/


All Articles