Posts

Showing posts with the label completable future

Enjoy quickies with supplyAsync by knowing how to handle exceptions.

PROBLEM: I have a method:  public String getChuckNorrisFact(); This method may also throw an exception, in my case IOException because this method does a service call to get a fact about Chuck Norris from web. I learned about  CompletableFuture  and now I am ASYNCING the shit out everywhere. Here is what I did: CompletableFuture<String> factFuture  = CompletableFuture.supplyAsync(() -> getChuckNorrisFact()); But the compiler tells me to handle or throw the exception, so I do this: CompletableFuture<String> factFuture2 = CompletableFuture.supplyAsync(() -> { try  { return getChuckNorrisFact(); } catch (IOException e ) { e .printStackTrace(); } }); Sadly there is still a compilation error in this. The supplier(lambda expression) in supplyAsync()  needs to return a string but there is no return statement if an exception occurs. So I do this: CompletableFuture...

Converting google/guava ListenableFuture to Java 8 CompletableFuture

Java was a bit late in bringing Javascript's promise-like functionality. Future was there but wasn't as cool. So people at google made ListenableFuture . Now that java has CompletableFuture , it is common to run into problems like converting a ListenableFuture to a CompletableFuture. This can be because part of your older code uses ListenableFuture and now you have to compose your new logics utilising the newer and Java native technique. Following is one possible way to do it. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class FutureConverter { public static CompletableFuture toCompletableFuture ( ListenableFuture listenableFuture ) { final CompletableFuture completableFuture = new CompletableFuture (); Futures . addCallback ( listenableFuture , new FutureCallback () { public void onFailure ( Throwable throwable ) { completableFuture . completeException...