How to cancel Spring @Async task?

889 Views Asked by At

I am using the following ThreadPoolTaskExecutor Configuration:

        @Bean(name = "asyncExecutor")
    public Executor asyncExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(150);
        executor.setQueueCapacity(150);
        executor.setThreadNamePrefix("AsyncThread-");
        executor.initialize();

        return executor;
    }

and using this in the service method:

    @Async("asyncExecutor")
    public void executeJob() {
    /// running job
    }

How can I kill/cancel the running task under @Async? Please share some examples, thanks

1

There are 1 best solutions below

0
HKBN-ITDS On

A good practice to implement @Async method is return a Future object from it. Because you need a connector between caller class and the task.

import java.util.concurrent.Future;
import org.springframework.scheduling.annotation.AsyncResult;

public class MyJob{
    @Async("asyncExecutor")
    public Future<String> executeJob() {
        // running job
        return new AsyncResult<>("Result");
    }
}

Now, you could do this in the caller class:

Future<String> jobTask = myJob.executeJob();
jobTask.cancel(true);

Note: .cancel(true) not guaranteed immediate effect. It will just call .interrupt(). It issues a flag so whenever in sleeping or waiting state, the thread will be stopped. Refer Thread.interrupt()

If you need to stop the thread immediately. And you have a long loop. You can just add a condition in the loop like below:

import java.util.concurrent.Future;
import org.springframework.scheduling.annotation.AsyncResult;

public class MyJob{
    private boolean stop;

    @Async("asyncExecutor")
    public Future<String> executeJob() {
        stop = false;
        while(!stop) {
            // running job
        }
        return new AsyncResult<>("Result");
    }

    public void setStop(Boolean stop) {
        this.stop = stop;
    }
}

And stop it in the caller like this:

myJob.setStop(true);