java dag,如何在Java中实现类似DAG的调度程序?

本文介绍如何使用Google Guava库的ListenableFuture和其allAsList方法,设计一个通用的DAG任务调度器,以简化Java中复杂任务间的依赖关系。不再需要频繁检查任务完成状态,通过Container类管理任务并自动等待依赖完成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I want to implement a simple DAG-like scheduler in Java (no result needed), described as the following graph:

M1ouR.png

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:

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.

I also checkout the Guava lib's ListenableFuture, but I don't know how to use it properly.

Any suggestions on how to implement a DAG, or recommending an existing opensource scheduler will be appreciated.

解决方案

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.

An example of using the allAsList, chain, and transform methods:

http://codingjunkie.net/google-guava-futures/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值