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
A good practice to implement
@Asyncmethod is return aFutureobject from it. Because you need a connector between caller class and the task.Now, you could do this in the caller class:
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:
And stop it in the caller like this: