如何在Java中实现类似DAG的调度程序? [英] How to Implement a DAG-like Scheduler in Java?
问题描述
我想在Java中实现一个简单的类似DAG的调度程序(无需结果),如下图所示:
I want to implement a simple DAG-like scheduler in Java (no result needed), described as the following graph:
我可以简单地使用手动代码来实现这个目的:
I can simply use manual code to achieve this:
ExecutorService executor = Executors.newCachedThreadPool();
Future<?> futureA = executor.submit(new Task("A"));
Future<?> futureC = executor.submit(new Task("C"));
futureA.get();
Future<?> futureB = executor.submit(new Task("B"));
futureB.get();
futureC.get();
Future<?> futureD = executor.submit(new Task("D"));
futureD.get();
但我正在寻找更通用的方法来做到这一点,所以我可以使用调度程序这个:
But I'm looking for a more general way to do this, so I can use the scheduler like this:
Container container = new Container();
container.addTask("A", new Task("A"));
container.addTask("B", new Task("B"), "A");
container.addTask("C", new Task("C"));
container.addTask("D", new Task("D"), "B", "C");
container.waitForCompletion();
实际上我已经实现了一个简单的:
And actually I've already implement a simple one:
但是我需要每隔100ms迭代一次所有任务,看看哪一个已准备好提交。同样在这个实现中没有异常检查。
But I need to iterate all the tasks every 100ms to see which one is ready to be submitted. Also in this implementation there's no exception checking.
我也检查了Guava lib的ListenableFuture,但我不知道如何正确使用它。
I also checkout the Guava lib's ListenableFuture, but I don't know how to use it properly.
任何有关如何实施DAG或推荐现有开源调度程序的建议都将受到赞赏。
Any suggestions on how to implement a DAG, or recommending an existing opensource scheduler will be appreciated.
推荐答案
你正在寻找的东西可以使用google的guava库来完成,它是可听的未来界面。 ListenableFutures允许您拥有复杂的异步操作链。一旦使用allAsList方法完成任务B和C,你应该实现一个可听的未来来执行任务D.
What you're looking for can be done using the google's guava library and it's listenable future interface. ListenableFutures allow you to have complex chains of asynchronous operations. You should implement a listenable future to execute task D once task B and C are completed using the allAsList method.
可听期货的文件:
https://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained
关于可听期货的教程:
http://www.javacodegeeks.com/2013/02/listenablefuture-in-guava.html
A tutorial on Listenable Futures: http://www.javacodegeeks.com/2013/02/listenablefuture-in-guava.html
使用allAsList,chain和transform方法的示例:
http://codingjunkie.net/ google-guava-futures /
An example of using the allAsList, chain, and transform methods: http://codingjunkie.net/google-guava-futures/
这篇关于如何在Java中实现类似DAG的调度程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!