title: Java VM suddenly exiting without apparent reason
body: <p>I have a problem with my Java progam suddenly exiting, without any exception thrown or the program finishing normally.</p>
  
  <p>I'm writing a program to solve <a href="http://projecteuler.net" rel="nofollow noreferrer">Project Euler</a>'s <a href="http://projecteuler.net/index.php?section=problems&amp;id=14" rel="nofollow noreferrer">14th problem</a>. This is what I got:</p>
  
  <pre><code>private static final int INITIAL_CACHE_SIZE = 30000;
  private static Map&lt;Long, Integer&gt; cache = new HashMap&lt;Long, Integer&gt;(INITIAL_CACHE_SIZE);
  
  public void main(String... args) {
      long number = 0;
      int maxSize = 0;
  
      for (long i = 1; i &lt;= TARGET; i++) {
          int size = size(i);
          if (size &gt; maxSize) {
              maxSize = size;
              number = i;
          }
      }
  }
  private static int size(long i) {
      if (i == 1L) {
          return 1;
      }
      final int size = size(process(i)) + 1;
      return size;
  }
  
  private static long process(long n) {
      return n % 2 == 0 ? n/2 : 3*n + 1;
  }
  </code></pre>
  
  <p>This runs fine, and finishes correctly in about 5 seconds when using a TARGET of 1 000 000.</p>
  
  <p>I wanted to optimize by adding a cache, so I changed the size method to this:</p>
  
  <pre><code>private static int size(long i) {
      if (i == 1L) {
          return 1;
      }
      if (cache.containsKey(i)) {
          return cache.get(i);
      }
      final int size = size(process(i)) + 1;
      cache.put(i, size);
      return size;
  }
  </code></pre>
  
  <p>Now when I run it, it simply stops (process exits) when I get to 555144. Same number every time. No exception, error, Java VM crash or anything is thrown.</p>
  
  <p>Changing the cache size doesn't seem to have any effect either, so how could the cache 
  introduction cause this error?</p>
  
  <p>If I enforce the cache size to be not just initial, but permanent like so:</p>
  
  <pre><code>    if (i &lt; CACHE_SIZE) {
          cache.put(i, size);
      }
  </code></pre>
  
  <p>the bug no longer occurs. 
  Edit: When I set the cache size to like 2M, the bug starts showing again.</p>
  
  <p>Can anyone reproduce this, and maybe even provide a suggestion as to why it happens?</p>