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

时间:2018-02-21 05:01:28

标签: java akka actor

我是Akka工具包的新手。我需要在多个文件上运行一个需要相当长时间的进程。所以我为每个文件创建了一个actor并开始处理。我在POJO类中创建这些actor,如下所示:

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是actor类。在调用所有actor以退出程序之后,主进程在每30秒内检查所有actor是否完成。有没有更好的方法来实现这种功能?

0 个答案:

没有答案