cs4r
cs4r

Reputation: 624

Wait for an actor response indefinitely in a future akka java

I have a non-actor-based piece of code which delegates some operations to an akka actor and I would like to wait this actor response indefinitely, I mean, until this actor returns a response whatever time it takes. The problem is I have not idea how to wait indefinitely in a Future with Pattern.ask and Await.result methods.

I would prefer something like this:

Timeout timeout = new Timeout(Duration.inf());
Future<Object> future = Patterns.ask(actor, msg, timeout);
String result = (String) Await.result(future, timeout.duration());

but this does not work because Timeout does not accept a Duration object as constructor parameter, it only accepts FiniteDuration objetcs...

Any idea?

Cheers

Upvotes: 1

Views: 3101

Answers (2)

Sycomor
Sycomor

Reputation: 1272

Disclaimer : I'm not very experienced with Akka.

Suggestion : can't you forego the Timeout object and simply write

Future<Object> future = Patterns.ask(actor, msg);
Await.result(f, Duration.Inf);

Either that, or use Timeout timeout = Timeout.never

Beware, however :

A Timeout with infinite duration. Will never timeout. Use extreme caution with this as it may cause memory leaks, blocked threads, or may not even be supported by the receiver, which would result in an exception. (from the Akka API doc)

Upvotes: -1

jamesmulcahy
jamesmulcahy

Reputation: 308

You may never receive an answer, since message delivery is not 100% guaranteed. As such, waiting indefinitely isn't a good approach -- you could well end up waiting forever.

You probably want some level of timeout (perhaps a long one, if it suits), and then a fallback case where you re-send your request as necessary. This would be the more robust way of handling this situation.

Upvotes: 6

Related Questions