处理Future onSuccess作为Akka演员的回应

时间:2013-05-17 15:19:00

标签: java akka

这是有效的代码。它向Actor(Greeter)发送消息并等待回复。 但它阻止了当前的线程。

public class Future1Blocking {

    public static void main(String[] args) throws Exception {

        ActorSystem system = ActorSystem.create("system");
        final ActorRef actorRef = system.actorOf(Props.create(Greeter.class), "greeter");

        Timeout timeout = new Timeout(Duration.create(5, "seconds"));
        Future<Object> future = Patterns.ask(actorRef, Greeter.Msg.GREET, timeout);

        // this blocks current running thread
        Greeter.Msg result = (Greeter.Msg) Await.result(future, timeout.duration());

        System.out.println(result);

    }
}

我的示例使用future.onSuccess获取结果而不阻塞当前调用线程的可行方法是什么?

1 个答案:

答案 0 :(得分:10)

稀释。这很容易(抱歉)。

future.onSuccess(new PrintResult<Object>(), system.dispatcher());

其中:

public final class PrintResult<T> extends OnSuccess<T> {
    @Override public final void onSuccess(T t) {
        System.out.println(t);
    }
}