How to use Akka Futures asynchronously in Java

I am making a call at the Java service level, which is as follows:

Future<Object> future = Patterns.ask(myActor, message, timeout); Response res = (Response) Await.result(future, timeout.duration()); 

I have read the Akka documentation and understand that blocking is not recommended. I need to return the response object to the calling method. Is it possible to do this asynchronously with Akka from my Java service? I tried to do this using the future.onSuccess method, however the onSuccess method onSuccess not allow the value to be returned, so I cannot return the value.

+5
source share
1 answer

A way to transfer data between akka threads, which is essentially what you do by blocking above, is to compose futures or send a message to the Actor.

The following example was 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()); 

Note that in this example, the data is "returned" or, more precisely, transferred to another unit of work without a thread that should block and wait for the result.

This is why onSuccess returns void, it should be used at the end of a chain of stacked futures. If he returned the value, it would be like a map, and it would return another Future. Which would leave you with the same lock requirement.

So, to answer your question, no. It is impossible to "return" a value from an asynchronous future without blocking. Instead, you should check why you need to respond so that it returns, and see if you can move Response processing to onSuccess or the map. A small alternative is to return Future [Response] and let the caller worry about binding futures. The case that you hit usually occurs when mixing paradigms, and it is better to avoid it.

+4
source

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


All Articles