The futility of futures using Guava?

Lately, I have been actively working with Google Guava and ListenableFutures, and something that I was missing was a way to provide a stream processing handler for future orders. What I represent is an iterable that blocks next () until another future returns.

Before I try to create my own, does it already exist?

Otherwise, I was thinking of using the ListenableFuture callback function to output the results to a BlockingQueue. The goal is to process the return values ​​as soon as they return. Futures.successfulAsList() excellent, but it waits for all the values ​​before returning, and does not allow me to schedule other useful work.

+4
source share
2 answers

You can use java.util.concurrent.CompletionService . His take method can easily be ported to Iterator.next() if he did not throw an InterruptedException .

+7
source

I think you could use the same trick I was looking with the .NET Task<T> :

  • Create new values List<SettableFuture<T>> - the same amount as the input futures
  • Keep a counter for “how many futures have completed”
  • For each input futures add a listener so that at the end of the future it increases the counter and sets this value (or error) for the corresponding element in the list
  • Return List to Caller

This is now a sequence of futures matching the input sequence, but in the order in which the inputs end. Then the caller can iterate through the list in turn, waiting for each of them to complete.

+1
source

Source: https://habr.com/ru/post/1432120/


All Articles