Is it possible to chain async calls using Guava?

匿名 (未验证) 提交于 2019-12-03 01:39:01

问题:

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

Is it possible to do it with guava?

回答1:

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 service1result = service1.submit(new Callable() {     @Override     public String call() throws Exception {         return "service1result";     } });  ListenableFuture service2result = Futures.chain(service1result, new Function>() {     @Override     public ListenableFuture apply(final @Nullable String input) {         return service2.submit(new Callable() {             @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 


回答2:

Futures.chain was removed in version 12.0. The new method of chaining together ListenableFutures is via the Futures.transform method.

https://github.com/google/guava/wiki/ListenableFutureExplained#application

From Guava latest javadoc (16.0.1 as of this writing).

ListenableFuture rowKeyFuture = indexService.lookUp(query); AsyncFunction queryFunction =    new AsyncFunction() {    public ListenableFuture apply(RowKey rowKey) {       return dataService.read(rowKey);    } }; ListenableFuture queryFuture = transform(rowKeyFuture, queryFunction); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!