背景:后置流程。例如:task1配置后置流程task2,task3。task3配置后置流程task4
问题:需要解决的问题配置时候防止回路,造成死循环:task1配置后置流程task2,task2配置后置流程task1
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class LoopDetection {
public static void main(String[] args) {
List<MyProcess> flowList = new ArrayList<>();
Integer processId = 1001;
List<Integer> checkList = new ArrayList<>();
Map<Integer,MyProcess> postMap = new HashMap<>();
getAllPostProcess(flowList,processId,checkList,postMap);
System.out.println("is ok");
}
private static MyProcess getProcess(Integer processId){
// 模拟数据库的数据
Map<Integer,MyProcess> mockDataBaseMap = new HashMap<>();
mockDataBaseMap.put(1001,new MyProcess(1001,"process01","1002,1003,1004"));
mockDataBaseMap.put(1002,new MyProcess(1002,"process02","1003"));
mockDataBaseMap.put(1003,new MyProcess(1003,"process03","1004"));
mockDataBaseMap.put(1004,new MyProcess(1004,"process04",null));
return mockDataBaseMap.get(processId);
}
private static void getAllPostProcess(List<MyProcess> flowList, Integer processId, List<Integer> checkList, Map<Integer, MyProcess> postMap){
MyProcess processById = null;
if(postMap!=null){
if(!postMap.containsKey(processId)){
processById = getProcess(processId);
postMap.put(processById.getId(),processById);
}else {
processById = postMap.get(processId);
}
}
if (processById!=null && processById.getId()!=null){
flowList.add(processById);
if (checkList.contains(processId)){
throw new RuntimeException("0,后置流程中存在死循环");
}
checkList.add(processId);
if (!"".equals(processById.getPostProcess()) && processById.getPostProcess()!=null){
for (String flowIdstr : processById.getPostProcess().split(",")) {
getAllPostProcess(flowList,Integer.parseInt(flowIdstr),checkList,postMap);
}
}
checkList.remove(processId);
}
}
}
class MyProcess{
private Integer id;
private String name;
private String postProcess;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPostProcess() {
return postProcess;
}
public void setPostProcess(String postProcess) {
this.postProcess = postProcess;
}
public MyProcess(Integer id, String name, String postProcess) {
this.id = id;
this.name = name;
this.postProcess = postProcess;
}
}