Search code examples
javaasynchronousguavafuture

How to log ListenableFuture returnType?


I have a code snippet like this

 public ListenableFuture<ProductCatalog> someAsync(List<someItem> someItemList) throws Exception {

    return ProductCatalog.someFunction()
            .executeAsync();
}

Now I want to log the header I will get from ProductCatalog. I know this is a asyncFunction and program will not wait for its response. But the problem is that I have to log the header without changing the method definition. Will this below execution do the trick or any otherway. I am new to this async functionality in java.

    public ListenableFuture<ProductCatalog> someAsync(List<someItem> someItemList) throws Exception {

    ListenableFuture<ProductCatalog> Lp = ProductCatalog.someFunction().executeAsync();
    ProductCatalog productCatalog = Lp.get();
    productCatalog.getHeader();
    return Lp;
}

Solution

  • When you're calling get() on a Future execution will block until the result is ready or execution has failed so this will break your call (i.e. it won't be async anymore).

    However, the prefix "Listenable" indicates you can add listeners on the future, e.g. like this:

    Lp.addCallback(product -> log(product.getHeader()), error -> log(error));
    

    This makes use of lambdas which basically implement the SuccessCallback and FailureCallback interfaces.

    Your method would thus look like this:

    public ListenableFuture<ProductCatalog> someAsync(List<someItem> someItemList) throws Exception {
      ListenableFuture<ProductCatalog> Lp = ProductCatalog.someFunction().executeAsync();
      Lp.addCallback(product -> log(product.getHeader()), error -> log(error));
      return Lp;
    }