Spring Cancel @Async Task

I want to be able to cancel the method marked with @Async annotation future.

I have a Spring method tagged with @Async annotation. This method performs some calculations and ultimately returns the result. All the examples I've seen recommend using the AsyncResult class to bring this Future back.

 @Async public Future<String> run() { // ... Computation. Minutes pass ... return new AsyncResult<String>("Result"); } 

I call the following method from another Component as follows. For example, I want to cancel this thread immediately:

 Future<String> future = component.run(); future.cancel(true); 

In this case, the thread will never be undone. This is because looking at the Spring implementation for AsyncResult here: https://github.com/spring-projects/spring-framework/blob/master/spring-context/src/main/java/org/springframework/scheduling /annotation/AsyncResult.java#L71 , this method actually does nothing, It simply returns false that the thread cannot be undone. That's my problem. How can I undo Thread created by @Async ? I donโ€™t have access to the internal branch created by Spring - so I donโ€™t have the means to cancel it, right?

+5
source share
1 answer

Actually, Spring @Async uses its own thread pool. And as long as the cancel () method of the Future or shutdownNow () function of the executing service, Calling executor.shutdownNow() or future.cancel(true) does not stop the current thread immediately. What these methods do is simply call .interrupt() on the appropriate thread (s). And interrupts has no guaranteed immediate effect . It issues a flag, so whenever it is in the idle or idle state, the thread stops.

It should be noted that if your tasks ignore interruption, executor.shutdownNow() and future.cancel(true) will behave exactly like executor.shutdown() and future.cancel(false) .

If you need a way to stop a slow or blocking operation. If you have a long / infinite loop, you can simply add the condition: Thread.currentThread().isInterrupted() and not continue if it is true (completion of the operation).

+6
source

All Articles