Skip to content

Gracefull shutdown don't throw interrupted exception after timeout #34476

Closed as not planned
@deblockt

Description

@deblockt

Using graceful shutdown with async task ran with

CompletableFuture
                .runAsync(() -> {
                    
                }, executor)

Using @EnableScheduling and the executor applicationTaskExecutor the graceful shutdown don't take in account the currently running tasks, when the server shutdown the task is silently aborted (no InteruptedException).

Using a custom Executor:

ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(2);
        taskExecutor.setMaxPoolSize(2);
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        taskExecutor.setAwaitTerminationSeconds(1);
        taskExecutor.setVirtualThreads(true);
        taskExecutor.initialize();

The graceful shutdown wait 1 second before the end of the task, and the log [WARN] - Forcing shutdownNow() - Tasks did not stop in time. is displayed. But no InterruptedException is thrown in the Runnable.

To have an InterruptedException I should create a scheduler like that

 ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(2);
        taskExecutor.setMaxPoolSize(2);
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        taskExecutor.setAwaitTerminationSeconds(1);
        taskExecutor.setVirtualThreads(true);
        taskExecutor.initialize();

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                log.info("Waiting for executor to terminate...");
                ThreadPoolExecutor executor = taskExecutor.getThreadPoolExecutor();
                if (executor != null) {
                    if (!executor.awaitTermination(1, TimeUnit.SECONDS)) {
                        log.warn("Forcing shutdownNow() - Tasks did not stop in time.");
                        executor.shutdownNow();
                    }
                }
            } catch (InterruptedException e) {
                log.error("Shutdown hook interrupted!", e);
                Thread.currentThread().interrupt();
            }
        }));

Doing that the graceful shutdown wait 1 second and stop the task with an InterruptedException.

The goal of the InterruptedException is to be able to log the stopped task, to know that something should be retry.

Why the default ThreadPoolTaskExecutor don't offer a way to have an InterruptedException. Is it possible to add this feature? To avoid to write it manually ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    in: coreIssues in core modules (aop, beans, core, context, expression)status: invalidAn issue that we don't feel is valid

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions