AHH
AHH

Reputation: 1083

Schedule a CompletionStage in Akka

I am writing utilities that manage CompletionStages and need to schedule a CompletionStage using Akka. Is there a way to give Akka a CompletionStage and ask it to run it later?

I usually use actors like this:

class MyActor extends UntypedActor {
    public void onReceive(Object msg) throws Exception {
        doTheWork();
    }
}

final ActorRef ref = system.actorOf(Props.create(MyActor.class, this));

system.scheduler().schedule(Duration.Zero(), ref, "Test", system.dispatcher(), null);

Is there a way to give Akka a CompletionStage to run without completing the stage explicitly in the actor like this:

class MyActor extends UntypedActor {
    public void onReceive(Object msg) throws Exception {
        myStage.toCompletableFuture().get();
    }
}

Upvotes: 1

Views: 486

Answers (1)

johanandren
johanandren

Reputation: 11479

I think there is a bit of misunderstanding of the CompletionStage API going on here, the completion stage does not run anywhere, there may be logic that will complete it that runs on some thread, and there may be callbacks triggered on completion and those are also run on some thread.

Here are a few sample interactions with a CompletableFuture/CompletionStage that uses the Akka dispatcher for the actual execution:

final CompletableFuture<Integer> futureInt = new CompletableFuture<>();

// right away but on the Akka default dispatcher
system.dispatcher().execute(() -> {
  futureInt.complete(5);
});

// or later using the Akka scheduler
system.scheduler().scheduleOnce(FiniteDuration.create(5, TimeUnit.SECONDS), () -> {
  futureInt.complete(6);
}, system.dispatcher());


// run some logic _when_ the completion stage is completed
futureInt.thenAcceptAsync((n) -> {
  System.out.println("futureInt completed with value " + n);
}, system.dispatcher());

Upvotes: 1

Related Questions