title: Java Stackoverflow
body: <p>I created an application to intentionally trigger <code>StackOverflowError</code>s, and it is exhibiting some strange behavior.  My application relies on a recursive method, and this method has a base case for terminating the recursion: it increments a variable in a <code>while</code> loop until its value equals or exceeds a hardcoded target value.  The strange behavior is that the minimum target value necessary to trigger a stack overflow is not consistent from run to run.  Why might that be?</p>
  
  <p>Here's the code:</p>
  
  <pre><code>public class MyClass {
      private static MyClass appOne4 = new MyClass();
      private static int i = 0;
  
      public void causeStackoverflowException() {//Recursive Method
          System.out.println(i);
          while (i&lt;12000) {
              i++; //This works since variable "i" is static
              causeStackoverflowException();
          }
      }
  
      public static void main(String[] args) {
          appOne4.causeStackoverflowException();
      }
  }
  </code></pre>
  
  <p>Updated Code</p>
  
  <pre><code>public class MyClass {
      private static MyClass appOne4 = new MyClass();
      private static int i = 0;
  
      public static void main(String[] args) {
          appOne4.causeStackoverflowException(i);
      }
  
      public int causeStackoverflowException(int myI) {//Recursive Method
          System.out.println(myI);
          if(myI==10460) {//12000
              return myI;
          }
          if (myI&lt;12000) {
              myI++; //This works since variable "i" is static
              return causeStackoverflowException(myI);
          }
          return -1;////ERROR
      }
  
  }
  </code></pre>