5

If you have an @Async method the returns a CompletableFuture....and the future never gets completed, does spring just leak the thread? Yes, I know whomever is waiting on the results could timeout and assume exceptional completion for latter stages.....but that doesn't stop the thread. Even if you call cancel, it doesn't do shit to the running thread:

from the docs:

@param mayInterruptIfRunning this value has no effect in this implementation because interrupts are not used to control processing.

If I use Future instead of CompletableFuture, cancel will interrupt the thread. Unfortunately, there is no equivalent of "allOf" on Future like we have on CompletableFuture to wait for all the tasks, like so:

// wait for all the futures to finish, regardless of results
CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new))
   // if exceptions happened in any future, swallow them
   // I don't care because I'm going to process each future in my list anyway
   // we just wanted to wait for all the futures to finish
   .exceptionally(ex -> null); 
  1. how are we supposed to cancel a thread that we bailed on?
  2. if I didn't cancel it (somehow), would my pool just be down a thread forever????
Jason
  • 2,451
  • 2
  • 23
  • 31
  • would `.orTimeOut()` solve your problem? It would either complete or throw a TimeOut Exception. So if the thread is abandoned, the future would eventually timeout. https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/CompletableFuture.html#orTimeout-long-java.util.concurrent.TimeUnit- – Randy Casburn Oct 30 '20 at 00:50
  • not really....that still just bails on the CompletableFuture so the caller can move on....the thread of execution just keeps on chugging.... – Jason Oct 30 '20 at 15:12
  • Ah...misunderstood your intent. – Randy Casburn Oct 30 '20 at 15:13
  • Does this answer your question? [Spring Cancel @Async Task](https://stackoverflow.com/questions/38880069/spring-cancel-async-task) – Randy Casburn Oct 30 '20 at 15:25
  • I guess....I mean, it basically says "no, you can't". I'm still stunned that the springs docs don't seem to explicitly _tell_ you what happens if all the threads in the pool get leaked....or provide a clean / simple leak detection mechanism. – Jason Oct 30 '20 at 20:44
  • there isn't, yes. But it's not Spring to be blamed, it's the fact that a `CompletableFuture` can not be canceled, [without stopping the executor itself and hoping that the task responds to interrupts](https://stackoverflow.com/questions/64743332/stopping-a-thread-in-java-completablefuture-after-timeout/64815403#64815403) – Eugene Nov 19 '20 at 02:58

0 Answers0