Akka:在询问时丢失了对child.path.name的引用

时间:2019-03-04 04:54:44

标签: java akka completable-future actor-model

我正在尝试实现曼宁的《 Akka in Action》一书中的"Up and Running" example的Java版本。这是一个基于Actor模型的简单Http服务器,用于保存(仅在内存中)和检索某些事件。保存事件没有问题。但是在查询演员系统的事件(所有事件)时确实有问题。

这是BoxOffice的相关代码(我用三点代替我认为与我的问题无关的代码)-所有TicketSeller的父演员(以后负责)用于管理每个事件的状态。

public class BoxOffice extends AbstractActor {

    ...
    private Timeout timeout;
    final static String NAME = "boxOffice";

    //create child actors
    private ActorRef createTicketSeller(String name) {
        return getContext().actorOf(TicketSeller.props(name));
    }

    public BoxOffice(Timeout timeout) {
        this.timeout = timeout;
    }

    //the only method of an actor
    @Override
    public Receive createReceive() {
        return receiveBuilder()
                ...
                ...
                .match(GetEvent.class, this::receiveMsgGetEvent)
                .match(GetEvents.class, this::receiveMsgGetEvents)
                ...
                .build();
    }

    ...

    private void receiveMsgGetEvent(GetEvent getEvent) {
        Optional<ActorRef> maybeChild = getChildByName(getEvent.getName());
        log.info(String.format("Asking for event %s. Child is present: %s", getEvent.getName(), maybeChild.isPresent()));
        OptionalConsumer.of(maybeChild)
                .ifPresent(child -> child.forward(new TicketSeller.GetEvent(), getContext()))
                .ifNotPresent(() -> getSender().tell(Optional.empty(), getSelf()));
    }

    private void receiveMsgGetEvents(GetEvents getEvents) {
        //ask self() for each of the passed-in event
        List<CompletableFuture<Optional<Event>>> listFutureMaybeEvent =
                allChildrenStream()
                .map(child ->
                        ask(getSelf(), new GetEvent(child.path().name()), timeout)
                        .thenApply(obj -> (Optional<Event>) obj)
                        .toCompletableFuture())
                .collect(toList());

        CompletableFuture<Events> eventsFuture = toFutureEvents(listFutureMaybeEvent);
        pipe(eventsFuture, getContext().dispatcher()).to(sender());
    }

    private Stream<ActorRef> allChildrenStream() {
        return StreamSupport.stream(getContext().getChildren().spliterator(), false);
    }

    ...

    private CompletableFuture<Events> toFutureEvents(List<CompletableFuture<Optional<Event>>> futurePossibleEvents) {
        List<Event> events = futurePossibleEvents.stream()
                .map(CompletableFuture::join)
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(toList());
        return CompletableFuture.supplyAsync(() -> new Events(events));
    }

    ...

    private Optional<ActorRef> getChildByName(String name) {
        return getContext().findChild(name);
    }

    static Props props(Timeout timeout) {
        return Props.create(BoxOffice.class, () -> new BoxOffice(timeout));
    }

基本上发生的是,在receiveMsgGetEvents中,我正在向self发送一条消息,消息中包含一个子名称child.path.name。但是,当我收到该消息(分别在receiveMsgGetEvent中)时,找不到该名称的子演员:

INFO  [BoxOffice]: Asking for event $a. Child is present: false

另外,值得注意的是,GetEvent的发送和接收由同一行为者花费的时间相当长(例如秒,但我感觉不到20)。

问题可能是由于我的CompletableFutures操纵所致,但是我试图重现scala等效代码。

上面的信息日志以及以下消息:

INFO  [DeadLetterActorRef]: Message [java.util.Optional] from Actor[akka://mycompanyAkkaDemo/user/boxOffice#1554115585] to Actor[akka://mycompanyAkkaDemo/deadLetters] was not delivered. [1] dead letters encountered. This logging...

在配置了超时(20秒)之后打印的堆栈跟踪之后打印:

ERROR [ActorSystemImpl]: Error during processing of request: 'Ask timed out on [Actor[akka://mycompanyAkkaDemo/user/boxOffice#1554115585]] after [20000 ms]. Sender[null] sent message of type "com.mycompany.demo.messages.boxoffice.GetEvents".'. Completing with 500 Internal Server Error response. To change default exception handling behavior, provide a custom ExceptionHandler.
akka.pattern.AskTimeoutException: Ask timed out on [Actor[akka://mycompanyAkkaDemo/user/boxOffice#1554115585]] after [20000 ms]. Sender[null] sent message of type "com.mycompany.demo.messages.boxoffice.GetEvents".
    at akka.pattern.PromiseActorRef$.$anonfun$defaultOnTimeout$1(AskSupport.scala:595)
    at akka.pattern.PromiseActorRef$.$anonfun$apply$1(AskSupport.scala:605)
    at akka.actor.Scheduler$$anon$4.run(Scheduler.scala:140)
    ...
    at java.lang.Thread.run(Thread.java:748)
ERROR [OneForOneStrategy]: akka.pattern.AskTimeoutException: Ask timed out on [Actor[akka://mycompanyAkkaDemo/user/boxOffice#1554115585]] after [20000 ms]. Sender[null] sent message of type "com.mycompany.demo.messages.boxoffice.GetEvent".
java.util.concurrent.CompletionException: akka.pattern.AskTimeoutException: Ask timed out on [Actor[akka://mycompanyAkkaDemo/user/boxOffice#1554115585]] after [20000 ms]. Sender[null] sent message of type "com.mycompany.demo.messages.boxoffice.GetEvent".
    at java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:292)
    at java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:308)
    at java.util.concurrent.CompletableFuture.uniApply(CompletableFuture.java:593)
    ...
Caused by: akka.pattern.AskTimeoutException: Ask timed out on [Actor[akka://mycompanyAkkaDemo/user/boxOffice#1554115585]] after [20000 ms]. Sender[null] sent message of type "com.mycompany.demo.messages.boxoffice.GetEvent".
    at akka.pattern.PromiseActorRef$.$anonfun$defaultOnTimeout$1(AskSupport.scala:595)
    ... 11 common frames omitted

1 个答案:

答案 0 :(得分:1)

这里出问题的是调度程序受阻。

在JVM上,由操作系统线程支持的线程在内存和进程调度程序开销上都很昂贵。 Akka的优点之一是,它允许您在较少数量的线程上运行许多actor,从而可以更有效地使用线程。

这很棒,但这确实意味着您永远不要在actor内部执行阻塞调用。这里的CompletableFuture::join呼叫被阻止,这很可能是您遇到问题的原因。

通过避免阻塞调用和使用异步API(例如CompletableFuture.allOf),您的问题应该会消失。