Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Response.getWriter() should it be closed / flushed

When a web application I noticed there were cases where the resonse.getWriter() was called and output to it, this PrintWriter is never flushed nor closed.

There are no further writes, so I could probably flush or close it safely. The application seems to work fine without closing the writers and in org.apache.catalina.connector.CoyoteAdapter does call finishResponse()/finishRequest() anyway but this is the inner workings of tomcat and seems wrong to rely on.

Closing the writer seems wrong because I'm not sure if I actually opened the writer with the response.getWriter() call. (usually not I think)

Flushing seem more like a good idea, but I'm sure if this is considered the 'right' way.

Not doing any flush or close feels like I might leak resources in certain cases.

like image 434
pvgoddijn Avatar asked Jan 10 '23 15:01

pvgoddijn


1 Answers

You don't need to flush() or close() the Writer.

Here's what the Servlet 3.1 spec says:

5.6 Closure of Response Object

When a response is closed, the container must immediately flush all remaining content in the response buffer to the client. The following events indicate that the servlet has satisfied the request and that the response object is to be closed:

  • The termination of the service method of the servlet.
  • etcetera

From this we can infer that the response should be flushed when the service method either returns, or terminates due to an exception.

I can't find anything that states explicitly that you don't need to close() a response Writer. However, since the web container manages the sockets, it would be crazy for it to not shut them down properly at the point in the request lifecycle (or connection lifecycle ... if persistent connections are used). Hence, I think it is safe to assume that there wouldn't be a resource leak if you neglected to call close(). (Certainly, there wouldn't be for a well-engineered web container.)


On the other hand, if you know that the writer or output stream is the response stream / writer for the current request, there is no harm in your servlet code flushing and/or closing them at the end of the request processing.

like image 175
Stephen C Avatar answered Jan 18 '23 23:01

Stephen C