Some Eclipse Foundation services are deprecated, or will be soon. Please ensure you've read this important communication.

Bug 500381

Summary: Irrelevant ‘Potential resource leak’ in HttpServlet
Product: [Eclipse Project] JDT Reporter: Olivier Cailloux <olivier.cailloux>
Component: CoreAssignee: Stephan Herrmann <stephan.herrmann>
Status: CLOSED DUPLICATE QA Contact:
Severity: enhancement    
Priority: P3 CC: stephan.herrmann
Version: 4.7   
Target Milestone: ---   
Hardware: PC   
OS: Linux   
Whiteboard:

Description Olivier Cailloux CLA 2016-08-28 13:16:58 EDT
When writing Java Servlet code using the following common pattern, and when ‘Potential resource leak’ is configured as a compiler warning or error, eclipse indicates “Potential resource leak: 'out' may not be closed at this location”. However, this is in fact not a problem in that specific context, as the container will close the stream when reaching the end of the method.

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletOutputStream out = resp.getOutputStream();
    out.print("Stuff.");
  }

To make eclipse warning disappear, one can annotate the method with ‘@SuppressWarnings("resource")’, but that has disadvantages. (Namely, collaborators not using eclipse may find it odd, it clutters the code because this will be needed on every servlet methods, and it hides possibly useful other warnings in the same category.)

I observe that it is not entirely consensual to use the above pattern leaving the closing part to the container, rather than close it in the code, which would solve the problem of course. (See http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter.) But it is certainly one reasonable option.

It seems to me this is an instance of a more general problem. Think about a wrapper class that opens a stream, makes it available to third-parties using a #getStream() method, but does not expect those third-parties to close the stream, as the wrapper class will close it when required. Then, I guess eclipse will similarly print a warning each time someone uses the getStream() method? (I haven’t tested.)

To solve this problem of irrelevant warnings, would it make sense to permit a developer to give a list of methods producing streams, that eclipse must ignore when warning about non-closed streams? Those methods would then be understood as methods that only hand out a reference to a pre-existing stream rather than a newly produced one.
Comment 1 Stephan Herrmann CLA 2016-08-28 13:27:16 EDT
The cleanest solution to problems of this kind would be to support one or more annotations for specifying ownership of the resource.

*** This bug has been marked as a duplicate of bug 495856 ***