Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set future from callback

I want to achieve what the following pseudo code illustrates:

int functionA() {
    Future res;
    // ...
    setCallbackForSomething(new Callback() {
        public void onCall() {
            // ...
            res = 5;
        }
    });
    // ...
    return doSomethingElse(res.get());
}

i.e. the functionA blocks until the callback has been called, then processes the result and returns something.

Is something like that possible with Future? The usual usage,

Future res = executor.submit(...);
...
res.get()

does not seem to work here. I also cannot change the fact that I have to set the callback like this.

like image 387
PhilLab Avatar asked Jan 06 '16 15:01

PhilLab


1 Answers

Future has limited features. From the javadoc

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.

It only exposes read operations (except for cancel). You won't be able to achieve what you want with Future.

Instead, since Java 8, you can use CompletableFuture

A Future that may be explicitly completed (setting its value and status), and may be used as a CompletionStage, supporting dependent functions and actions that trigger upon its completion.

You initialize the CompletableFuture

CompletableFuture<Integer> res = new CompletableFuture<>();

and complete it either normally or exceptionally

setCallbackForSomething(new Callback() {
    public void onCall() {
        // ...
        res.complete(5); // or handle exception
    }
});

Instead of calling get, you can chain a completion task on the CompletableFuture to call doSomethingElse.

res.thenAccept(value -> doSomethingElse(value));

Though you can still call get if you want to, blocking until the future is completed.


Before Java 8, the Guava library provided SettableFuture to achieve the "set" part of a promised value. But it's also a ListenableFuture so you can chain other operations on completion.

like image 170
Sotirios Delimanolis Avatar answered Oct 07 '22 00:10

Sotirios Delimanolis