如何检查所有演员是否完成

How to check if after all actors are finished

我是 Akka 工具包的新手。我需要 运行 处理多个文件,这需要花费大量时间。所以我为每个文件创建了一个演员并开始处理。我正在 POJO class 中创建这些演员,如下所示:

public class ProcessFiles {
    private static final Logger logger = LoggerFactory.getLogger(ProcessFiles.class.getSimpleName());

    public static void main(String[] args) throws IOException, InterruptedException {
        long startTime = System.currentTimeMillis();

        logger.info("Creating actor system");
        ActorSystem system = ActorSystem.create("actor_system");

        Set<String> files = new HashSet<>();
        Stream<String> stringStream = Files.lines(Paths.get(fileName));
        stringStream.forEach(line -> files.addAll(Arrays.asList(line.split(","))));
        List<CompletableFuture<Object>> futureList = new ArrayList<>();

        files.forEach((String file) -> {
            ActorRef actorRef = system.actorOf(Props.create(ProcessFile.class, file));
            futureList.add(PatternsCS.ask(actorRef, file, DEFAULT_TIMEOUT).toCompletableFuture());
        });

        boolean isDone;
        do {
            Thread.sleep(30000);
            isDone = true;
            int count = 0;
            for (CompletableFuture<Object> future : futureList) {
                isDone = isDone & (future.isDone() || future.isCompletedExceptionally() || future.isCancelled());
                if (future.isDone() || future.isCompletedExceptionally() || future.isCancelled()) {
                    ++count;
                }
            }
            logger.info("Process is completed for " + count + " files out of " + files.size() + " files.");
        } while (!isDone);
        logger.info("Process is done in " + (System.currentTimeMillis() - startTime) + " ms");
        system.terminate();
    }
} 

这里,ProcessFile 是演员class。调用完所有actor退出程序后,主进程每隔30秒检查一次所有actor是否完成。有没有更好的方法来实现这种功能?

我建议再创建一个 actor 来跟踪系统中所有 actor 的终止,并在所有 actor 都被杀死时关闭 actor 系统。 所以在你的申请中-

处理文件后,ProcessFile actor 可以向自己发送毒丸。 WatcherActor 将监视 (context.watch(processFileActor)) ProcessFileActor 并维护所有注册的 ProcessFile actor 的计数。

在演员终止时,WatcherActor 将收到 Terminated 消息。 它会减少计数,当计数达到0时,关闭ActorSystem。