title: Proper way of streaming using ResponseEntity and making sure the InputStream gets closed
body: <p>One of our application leaks file handles and we have not yet found the cause for this.</p>
  
  <p>In the code I can see several functions similar to this:</p>
  
  <pre><code>public ResponseEntity&lt;InputStreamResource&gt; getFoo( ... ) {
      InputStream content = getContent(...)
      InputStreamResource isr = new InputStreamResource(content);
      return ResponseEntity.status(HttpServletResponse.SC_OK).body(isr);
  }
  </code></pre>
  
  <p>(<code>if</code> checks and <code>try</code> / <code>catch</code> removed for brevity)</p>
  
  <p>I am sure this section causes the problem because when I loadtest this specific code with JMeter I can see that <code>getContent()</code> fails in this stage:</p>
  
  <pre><code>is = Files.newInputStream(f.toPath());
  </code></pre>
  
  <p>Normally I would close the <code>InputStream</code> but because this short and simply code I can't close the stream before <code>return</code> or the call of <code>body</code>.</p>
  
  <p>When I run <code>lsof</code> (the code runs on Linux) I can see that thousands of files are open in read mode. So I am sure this problem is caused by the stream not getting closed.</p>
  
  <p>Is there a best practice code I should trade in ?</p>