title: Resource leak in Files.list(Path dir) when stream is not explicitly closed?
body: <p>I recently wrote a small app that periodically checked the content of a directory. After a while, the app crashed because of too many open file handles. After some debugging, I found the error in the following line:</p>
  
  <pre class="lang-java prettyprint-override"><code>Files.list(Paths.get(destination)).forEach(path -&gt; {
       // To stuff
  });
  </code></pre>
  
  <p>I then checked the javadoc (I probably should have done that earlier) for <code>Files.list</code> and found:</p>
  
  <pre><code>* &lt;p&gt; The returned stream encapsulates a {@link DirectoryStream}.
  * If timely disposal of file system resources is required, the
  * {@code try}-with-resources construct should be used to ensure that the
  * stream's {@link Stream#close close} method is invoked after the stream
  * operations are completed
  </code></pre>
  
  <p>To me, "timely disposal" still sounds like the resources are going to be released eventually, before the app quits. I looked through the JDK (1.8.60) code but I wasn't able to find any hint about the file handles opened by <code>Files.list</code> being released again.</p>
  
  <p>I then created a small app that explicitly calls the garbage collector after using <code>Files.list</code> like this:</p>
  
  <pre class="lang-java prettyprint-override"><code>while (true) {
      Files.list(Paths.get("/")).forEach(path -&gt; {
        System.out.println(path);
      });
      Thread.sleep(5000);
  
      System.gc();
      System.runFinalization();
  }
  </code></pre>
  
  <p>When I checked the open file handles with <code>lsof -p &lt;pid&gt;</code> I could still see the list of open file handles for "/" getting longer and longer.</p>
  
  <p>My question now is: Is there any hidden mechanism that should eventually close no longer used open file handles in this scenario? Or are these resources in fact never disposed and the javadoc is a bit euphemistic when talking about "timely disposal of file system resources"?</p>