如何在不阻塞的情况下等待事件发生?
How to wait for event to happen without blocking?
我希望我的 actor 等待某个事件发生,但我希望它仍能接收消息并继续处理消息。我怎样才能实现它?
我的代码如下:
class MyActor extends UntypedActor {
//onReceive implementation etc...
private void doSomething(ActorRef other){
String decision = (String) Await.result(ask(other, new String("getDecision"),1000), Duration.create(1, SECONDS));
while(decision.equals(""){
Thread.sleep(100)
decision = (String) Await.result(ask(other, new String("getDecision"),1000), Duration.create(1, SECONDS));
}
}
}
但这会阻止整个 actor,直到它收到正确的决定。我怎样才能在不阻止我的演员的情况下实现类似的目标?
这种代码很适合使用Futures
。
您可以在此处找到更多信息:http://doc.akka.io/docs/akka/snapshot/java/futures.html
在你的情况下,它看起来像:
final ExecutionContext ec = context().dispatcher();
private void doSomething(ActorRef other){
Future<Object> decision = (Patterns.ask(other, new String("getDecision"), 1000));
decision.onSuccess(new OnSuccess<Object>() {
public void onSuccess(Object result) {
String resultString = (String) result;
System.out.println("Decision: " + result);
}
}, ec);
}
你应该总是尽量避免 Await.result
就像你说的那样会导致线程阻塞。您可以使用 onSuccess
或 onComplete
等回调在未来 returns 时执行代码,而无需等待结果。
我希望我的 actor 等待某个事件发生,但我希望它仍能接收消息并继续处理消息。我怎样才能实现它?
我的代码如下:
class MyActor extends UntypedActor {
//onReceive implementation etc...
private void doSomething(ActorRef other){
String decision = (String) Await.result(ask(other, new String("getDecision"),1000), Duration.create(1, SECONDS));
while(decision.equals(""){
Thread.sleep(100)
decision = (String) Await.result(ask(other, new String("getDecision"),1000), Duration.create(1, SECONDS));
}
}
}
但这会阻止整个 actor,直到它收到正确的决定。我怎样才能在不阻止我的演员的情况下实现类似的目标?
这种代码很适合使用Futures
。
您可以在此处找到更多信息:http://doc.akka.io/docs/akka/snapshot/java/futures.html
在你的情况下,它看起来像:
final ExecutionContext ec = context().dispatcher();
private void doSomething(ActorRef other){
Future<Object> decision = (Patterns.ask(other, new String("getDecision"), 1000));
decision.onSuccess(new OnSuccess<Object>() {
public void onSuccess(Object result) {
String resultString = (String) result;
System.out.println("Decision: " + result);
}
}, ec);
}
你应该总是尽量避免 Await.result
就像你说的那样会导致线程阻塞。您可以使用 onSuccess
或 onComplete
等回调在未来 returns 时执行代码,而无需等待结果。