I've got some code that submits a request to another thread which may or may not submit that request to yet another thread. That yields a return type of Future<Future<T>>
. Is there some non-heinous way to immediately turn this into Future<T>
that waits on the completion of the entire future chain?
I'm already using the Guava library to handle other fun concurrency stuff and as a replacement for Google Collections and its working well but I can't seem to find something for this case.
To create a Future object, we need to instantiate Future class by passing an invoker function (usually an anonymous function or fat arrow function) whose job is to return a value or another Future object that returns a value. A Future object has then and catchError methods which are used to register callback functions.
When using Future<void> there is no need to explicitly return anything, since void is nothing, as the name implies. Also make sure you call deleteAll and writeAsString() using await .
get() method returns a Future object: Calling a function that returns a Future, will not block your code, that's why that function is called asynchronous. Instead, it will immediately return a Future object, which is at first uncompleted. Future<T> means that the result of the asynchronous operation will be of type T .
You can calculate future value with compound interest using this formula: future value = present value x (1 + interest rate)n. To calculate future value with simple interest, use this formula: future value = present value x [1 + (interest rate x time)].
Another possible implementation that uses the guava libraries and is a lot simpler.
import java.util.concurrent.*;
import com.google.common.util.concurrent.*;
import com.google.common.base.*;
public class FFutures {
public <T> Future<T> flatten(Future<Future<T>> future) {
return Futures.chain(Futures.makeListenable(future), new Function<Future<T>, ListenableFuture<T>>() {
public ListenableFuture<T> apply(Future<T> f) {
return Futures.makeListenable(f);
}
});
}
}
Guava 13.0 adds Futures.dereference
to do this. It requires a ListenableFuture<ListenableFuture>
, rather than a plain Future<Future>
. (Operating on a plain Future
would require a makeListenable call, each of which requires a dedicated thread for the lifetime of the task (as is made clearer by the method's new name, JdkFutureAdapters.listenInPoolThread
).)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With