检测异步任务编排中的循环依赖
拓扑排序:
/**
* 时间复杂度O(n+k)
* 检测是否有向无环图 true为无环,false为有环
* 1.建立入度表Map<Task,Integer>,入度为0的入队
* 2.队列不为空,任务出队,将该任务相邻任务入度-1
* 3.若入度为0,则加入队列
* 4.全部执行完后,任务count为map大小,则无循环依赖,否则有循环依赖
*/
private void isDAGraph(Map<String, Set<String>> map) {
if (map.isEmpty()) {
return;
}
Map<String, Integer> inDegree = new HashMap<>();
map.forEach((k, v) -> inDegree.
computeIfAbsent(k, i -> v.size()));
Queue<String> queue = new LinkedList<>();
for (String key : inDegree.keySet()) {
if (inDegree.get(key).equals(0)) {
queue.offer(key);
}
}
int count = 0;
while (!queue.isEmpty()) {
String task = queue.poll();
count++;
for (String key : map.keySet()) {
if (map.get(key).contains(task)) {
inDegree.put(key, inDegree.get(key) - 1);
if (inDegree.get(key).equals(0)) {
queue.offer(key);
}
}
}
}
if (map.size() == count) {
return;
}
throw new RuntimeException(" is not DAGraph");
}