I'm making a call in a Java service layer that looks like this;
Future<Object> future = Patterns.ask(myActor, message, timeout);
Response res = (Response) Await.result(future, timeout.duration());
I've read the Akka documentation and realize blocking like this is not recommended. I need to return the response object to the calling method. Is it possible do this asynchronously with Akka from my Java service? I tried to do this using the future.onSuccess
method however the onSuccess
method does not allow a return value so I can't return the value.
The akka way of passing data between threads, which is essentially what you are doing by blocking above is to compose futures or to send a message to an Actor.
The following example has been taken from the Akka documentation.
final ExecutionContext ec = system.dispatcher();
Future<String> f1 = future(new Callable<String>() {
public String call() {
return "Hello" + "World";
}
}, ec);
Future<Integer> f2 = f1.map(new Mapper<String, Integer>() {
public Integer apply(String s) {
return s.length();
}
}, ec);
f2.onSuccess(new PrintResult<Integer>(), system.dispatcher());
Notice that in this example data is being 'returned', or more precisely it is being handed off to another unit of work without a thread having to block and wait for a result.
This is why onSuccess returns void, it is to be used at the end of a chain of composed futures. If it was to return a value, it would be like map and it would return another Future. Which would leave you with the same requirement of blocking.
Thus to answer your question, no. There is no way to 'return' a value from an asynchronous future without blocking. Instead you should review why you need Response to be returned like that, and see if instead you can move the handling of Response into either onSuccess or map. A minor alternative is to return Future[Response] and let the caller worry about chaining the futures. The case that you have hit usually happens when mixing paradigms, and it is best avoided.
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