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?

2

1 Answer 1

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.

3
  • I am using Tomcat 5.5 and i didnt found the any mention of this as in their docs
    – ajduke
    Oct 18, 2011 at 9:06
  • therefore you don't close it ;)
    – Bozho
    Oct 18, 2011 at 9: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 2, 2014 at 22:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.