title: Java Memory leak: Why are unreachable objects not collected?
body: <p>I am trying to find a workaround for the JDK Nashorn bug <a href="https://bugs.openjdk.java.net/browse/JDK-8229011" rel="nofollow noreferrer">JDK-8229011</a>.</p>
  <p>I reproduced the error with the script linked in the bug ticket and took several heap dumps. I used JProfiler and Eclipse Memory Analyzer
  to find the root of the problem. But, I always end up in unreachable paths and I don't understand why the objects are not garbage collected. AFAIS there are no finalizers to keep them alive.
  If I open the heap dump in JProfiler without disabling &quot;Full GC on Dump&quot;, JProfiler will even throw the unreachable objects away. But the GC itself won't. I tested with G1 GC, but its the same with CMS.</p>
  <p>You can get a sample dump in 1-2 minutes with any JDK &gt; 8 by running the following script with the settings: <code>-Xmx20M -XX:+HeapDumpOnOutOfMemoryError</code></p>
  <pre><code>public class TestJsMemLeak
  {
      public static final class JsJavaUtil
      {
          private long counter = 0;
  
          public long testFunc()
          {
              return counter++;
          }
      }
  
      public static void main(final String[] args) throws Exception
      {
          System.setProperty(&quot;nashorn.args&quot;, &quot;--no-java -doe -ot=false --language=es6 --no-deprecation-warning --lazy-compilation=false&quot;);       
          for (long i = 0; true; ++i)
          {
              final ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName(&quot;nashorn&quot;);
              scriptEngine.put(&quot;JsJavaUtil&quot;, new JsJavaUtil());
              scriptEngine.eval(&quot;for (var i = 0; i &lt; 10; ++i) {\n&quot; + &quot; JsJavaUtil.testFunc();\n&quot; + &quot;}&quot;);
              System.gc();
              if (i % 100 == 0)
              {
                  System.out.println(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
              }
          }
      }
  }
  </code></pre>
  <p>Running this will lead to a dump with an about 6-7 MB of unreachable java.lang.ClassValue$ClassValueMap</p>
  <p>I am looking for some hints, what is keeping these objects alive.</p>