0

I'm curious to the behavior of a CompletableFuture, that has been set to a different Executor, when it goes out of scope of the method that supplied it.

Say, for instance, that the following code fragment is being used:

public List<String> someMethod(ExecutorService service){
   List<String> myData = this.getMyData();
   CompletableFuture.supplyAsync(() -> this.doSomethingWithMyData(myData), service)
     .thenApplyAsync(this::doSomeTransformation)
     .thenAcceptAsync(this::consumeResults)
     .orTimeout(5, TimeUnit.MINUTES);

   return myData;
}

Assuming this is long running concurrent job,, would the CompletableFuture (and it's chain of async functions) still get completely executed after the method returns? This is assuming the overall application is still running in that timeframe (a RESTful service, for example).

My gut tells me that it would still run after the method returns, but I haven't seen the answer to this, so I'm hoping for some validation of that guess.

Savior
  • 3,225
  • 4
  • 24
  • 48
piper1970
  • 518
  • 1
  • 3
  • 14
  • 1
    Yes, of course, because the async job still has a reference to the `CompletableFuture`, otherwise how would it know about the chain? – Andreas Aug 28 '20 at 14:23
  • 2
    Does this answer your question? [CompletableFuture and Garbage Collection](https://stackoverflow.com/questions/54714299/completablefuture-and-garbage-collection) – Savior Aug 28 '20 at 14:35
  • 2
    The garbage collector identifies memory for reuse, it does not cancel jobs. By the way, when you use `thenApplyAsync` and `thenAcceptAsync` without specifying an executor, these methods will use the *default* executor, regardless of what executor you’ve specified for `supplyAsync`. In other words, they will *not* use `service`. Further, `orTimeout` will only complete the future you invoked it on, i.e. the `thenAcceptAsync(this::consumeResults)` stage. It will not prevent the execution of `doSomeTransformation`. – Holger Aug 28 '20 at 16:49
  • Thank you all for your answers to this question. I suspected as much, but wanted to get some other feedback. @Holger, thank you for the additional info on use of async functions w/o an explicit executor. It turns out, that's what I've been doing, so I will definitely adjust my code to do what I want it to do. – piper1970 Aug 29 '20 at 15:37

0 Answers0