使用计数器解决循环依赖无限循环?

Solving Circular Dependency infinite loop using counter?

我下面有2个methods

在正确的用例中,cancelChildTree() 调用 removeChildRelationsIfNecessary(),然后继续执行我的代码。

但是对于我数据库中的某些数据,父子之间存在 circular dependency。这导致 2 种方法在 infinite loop 中不断相互调用。

我该如何解决这个问题?我的计划是尝试添加一个 counter 来检测是否正在发生 infinite 循环 - 然后继续处理特定的父子关系。

方法一:

private void cancelChildTree(Parent parent) {
  removeChildRelationsIfNecessary(parent);
  //Note that the 2 methods below never get called if the infinite loop occurs
  otherMethod();
  anotherMethod();
}

方法二:

 private void removeChildRelationsIfNecessary(Parent parent) {
    List<Child> childList = parent.getParentChildRelationship()); 
    for (Child child: childList {
      cancelChildTree(child);
    }
  } 

您似乎在 同一个 对象上重复调用 cancelChildTree(Parent parent)

如果是这样,是什么阻止您使用某些 Set<Parent> 对象来跟踪提供给该方法的父对象?换句话说:而不是使用哑计数器;你为什么不跟踪那些当前正在处理的对象;避免再次处理它们