13

I wrote a simple servlet as follows:

public class MyServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        // [do stuff with the PrintWriter]
        out.close();
    }
}

Is it necessary to close the PrintWriter out stream? If I don't close the stream will that affect anything further?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
ajduke
  • 4,991
  • 7
  • 36
  • 56
  • 1
    Possible dup: http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter – Gustav Barkefors Oct 18 '11 at 08:24
  • possible duplicate of [Should I close the servlet outputstream?](http://stackoverflow.com/questions/1829784/should-i-close-the-servlet-outputstream) – BalusC Oct 18 '11 at 13:42

1 Answers1

19

If it's not you that's opening the stream, you should not close it.

The stream is opened by the container so the responsibility for closing lies with it.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • I am using Tomcat 5.5 and i didnt found the any mention of this as in their docs – ajduke Oct 18 '11 at 09:06
  • therefore you don't close it ;) – Bozho Oct 18 '11 at 09:07
  • 1
    I had a ton of grief in Tomcat, under heavy traffic, when my application was closing PrintWriter streams. Don't flush() either, unless you know why you're doing it. Otherwise you override the containers buffering mechanism. – Hal50000 Oct 02 '14 at 22:09