tags:

views:

380

answers:

2

Am I responsible for closing the HttpServletResponse.getOutputStream() (or the getWriter() or even the inputstream) or should I leave it to the container ?

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
   throws ServletException, IOException {
    OutputStream o = response.getOutputStream();
    ... 
    o.close(); //yes/no ?
}
+3  A: 

No you don't need to close it. If you do you basically end the response to the client. After closing the stream you can send anything else to the client until the next request. You didn't open the stream, so you don't have to close it.

Jeremy Raymond
Right. Just like on a farm: leave the gates exactly as you found 'em.
erickson
+7  A: 

You indeed don't need to do so. Thumb rule: if you didn't open it yourself, you don't need to close it yourself. If it was for example a new FileOutputStream("c:/foo.txt") then you obviously need to close it yourself.

Reasons that some people still do it are just to ensure that nothing more will be written to the stream. If it would ever happen, this will cause an IllegalStateException in the appserver logs, but this wouldn't affect the client. This is also an easier debug to spot the potential problems in the request-response chain which you wouldn't see at first glance.

Another reason which you see among starters is that they just wanted to prevent that more stuff is written into the response. You see this often when JSP incorrectly plays a role in the response. They just swallow the IllegalStateExceptions and ignore them further. Needless to say that this particular purpose is bad.

BalusC