ListenableFuture - 接收到集群中的消息并执行耗时代码后完成

ListenableFuture - finish after message in cluster is received and time consuming code is executed

起初我只想说我是akka和Futures的新手。所以要温柔 :).

我在 class returns ListenableFuture<Boolean> 中有初始化方法。这个方法应该在单独的线程中执行一些耗时的代码,并创建正在监听 akka 集群中的一些消息的 akka actor。 init 方法返回的 Future 应该在此 actor 收到特定消息并且耗时代码完成后完成。

如何使用 Guava 的 ListenableFuture 实现此目的?

请参阅 Akka 关于期货的文档:http://doc.akka.io/docs/akka/current/java/futures.html

您可以创建 2 个不同的 futures,一个执行耗时的代码:

Future<String> f1 = future(new Callable<String>() {
  public String call() {
    return "Hello" + "World";
  }
}, system.dispatcher());

另一个发送消息给演员 ask:

Timeout timeout = new Timeout(Duration.create(5, "seconds"));
Future<Object> f2 = Patterns.ask(actor, msg, timeout);

最后,你可以使用 Future.sequence 创建一个单一的未来,当你的两个未来都完成时,它就会完成。

Iterable<Future<Integer>> listOfFutureInts = source;
Future<Iterable<Integer>> futureListOfInts = sequence(listOfFutureInts, ec);

我是这样解决的。我创建了包含耗时代码的 ListenableFuture。在这个 furute 结束时,我创建了 CountDownLatch 并将它(使用 creator)传递给 akka actor。这个可听的未来后来被 countDownLatch.await() 屏蔽了。创建带有注入锁存器的actor,然后监听集群中的特定消息。在使用了这条特定消息后,我调用了 countDownLatch.countDown()。这解锁了未来,await() 在哪里被调用,未来完成并返回值。