2017-10-19 31 views
1

我在編寫管理CompletionStages的工具,需要使用Akka安排CompletionStage。有沒有辦法讓Akka成爲CompletionStage,並讓它稍後運行它?在Akka安排完成階段

我通常使用的演員是這樣的:

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); 

有沒有辦法讓阿卡一個CompletionStage到沒有演員像這樣明確地完成了階段運行:

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

回答

1

我想有對這裏的CompletionStage API有些誤解,完成階段不會在任何地方運行,可能有邏輯會完成它在某個線程上運行,並且可能會在完成時觸發回調,並且還會在某些線。

下面是與使用阿卡調度的實際執行的CompletableFuture/CompletionStage幾個樣品相互作用:

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());