0

Depending on how you view it the CompletableFuture API leaves a lot to be desired, but one the most irritating things for me, which I come across over and over again, is that it is trivial to construct a normally completed future in one line:

return CompletableFuture.completedFuture(result);

yet it is very verbose to construct an exceptionally completed future:

CompletableFuture<T> res = new CompletableFuture<>();
res.completeExceptionally(theCause);
return res;

Am I missing something and there is somewhere a sensible one-liner on the existing API or is the API really half-backed? I know I can turn the above latter case into a utility, but such a utility should be on the API, given that the above former one is there.

Oleg Sklyar
  • 9,834
  • 6
  • 39
  • 62
  • 2
    What about `return CompletableFuture.completedFuture(null).completeExceptionally(theCause); ` ? – Vyncent May 18 '18 at 14:47
  • 1
    I'm very curious, apart from testing code, why would you want to create an exceptionally completed future? How often do you do that that you consider turning it into a utility function? – M. le Rutte May 18 '18 at 14:50
  • @M.leRutte for asynchronous chains and APIs defined on completable future these are very common cases e.g. https://github.com/teris-io/kite/blob/master/kite-rpc-vertx/src/main/java/io/teris/kite/rpc/vertx/HttpServiceInvokerImpl.java – Oleg Sklyar May 18 '18 at 14:54
  • @Vyncent Would be cool if `completeExceptionally` returned a new or this completed stage, but it returns a bool, so same 3 lines :( – Oleg Sklyar May 18 '18 at 14:59
  • @OlegSklyar If I glance through the code I see that an exception might be raised depending on the server's status code result, but not a future that is right away completed with an exception, without trying to do the expected work. – M. le Rutte May 18 '18 at 14:59
  • @M.leRutte Quite some thought was put into that code, also with respect to exception handling: this was **not the problem I was solving now**, this was example for you to show the use of exceptionally completed futures which you asked about. At the moment I just want a one liner please :) – Oleg Sklyar May 18 '18 at 15:03
  • I understand. My curiosity was about the use case for creating such a future right away. But I have no answer for you, I'm sorry. – M. le Rutte May 18 '18 at 15:05

0 Answers0