title: Circular dependency in Java constructors
body: <p>I have the following classes. </p>
  
  <pre><code>public class B 
  {
      public A a;
  
      public B()
      {
          a= new A();
          System.out.println("Creating B");
      }
  }
  </code></pre>
  
  <p>and </p>
  
  <pre><code>public class A 
  {
      public B b;
  
      public A()
      {
          b = new B();
          System.out.println("Creating A");
      }
  
      public static void main(String[] args) 
      {
          A a = new A();
      }
  }
  </code></pre>
  
  <p>As can be clearly seen, there is a circular dependency between the classes. if I try to run class A, I eventually get a <code>StackOverflowError</code>. </p>
  
  <p>If a dependency graph is created, where nodes are classes, then this dependency can be easily identified (at least for graphs with few nodes). Then why does the JVM not identify this, at least at runtime? Instead of a throwing <code>StackOverflowError</code>, JVM can at least give a warning before starting execution. </p>
  
  <p><strong>[Update]</strong> Some languages cannot have circular dependencies, because then the source code will not build. For example, <a href="https://stackoverflow.com/questions/623006/circular-dependencies-versus-dry">see this question</a> and the accepted answer. If circular dependency is a design smell for C# then why is it not for Java? Only because Java can(compile code with circular dependencies)?</p>
  
  <p><strong>[update2]</strong> Recently found <a href="http://www.jcarder.org/" rel="noreferrer">jCarder</a>. According to the website, it finds potential deadlocks by dynamically instrumenting Java byte codes and looking for cycles in the object graph. Can anyone explain how does the tool find the cycles?</p>