Search code examples
javaguava

Is it possible to chain async calls using Guava?


I want to chain async rest service calls and have single callback when they finished.

Is it possible to do it with guava?


Solution

  • You can use Futures.chain for chaining ListenableFutures:

    final ListeningExecutorService service1 = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(16));
    final ListeningExecutorService service2 = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(16));
    
    ListenableFuture<String> service1result = service1.submit(new Callable<String>() {
        @Override
        public String call() throws Exception {
            return "service1result";
        }
    });
    
    ListenableFuture<String> service2result = Futures.chain(service1result, new Function<String, ListenableFuture<String>>() {
        @Override
        public ListenableFuture<String> apply(final @Nullable String input) {
            return service2.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    return Joiner.on(" -> ").join(input, "service2result");
                }
            });
        }
    });
    
    System.out.format("Result: %s\r\n", service2result.get());
    

    Output of at the code above in the terminal:

    > run-main training.Training
    [info] Compiling 1 Java source to /home/remeniuk/projects/guava-training/target/scala-2.9.1/classes...
    [info] Running training.Training 
    Result: service1result -> service2result