Solving Circular Dependency infinite loop using counter?

419 Views Asked by At

I have the following 2 methods below.

In a correct use case cancelChildTree() calls removeChildRelationsIfNecessary() and then moves on through my code.

However for some data in my database, there is a circular dependency between parents and children. This is causing the 2 methods to keep calling one another in an infinite loop.

How can I solve this issue? My plan was to try and add a counter to detect that a the infinite loop was occurring - then move on for that particular parent child relationship.

Method 1:

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

Method 2:

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

There are 1 best solutions below

2
On BEST ANSWER

It looks like you are repeatedly calling cancelChildTree(Parent parent) on the same object.

If so, what prevents you from using some Set<Parent> object to keep track of parent objects that were given to that method? In other words: instead of using a dumb counter; why don't you keep track of those objects that are currently processed; to avoid processing them again?