Do I need to "flush" the OutputStream from the HttpServletResponse?
I already saw from to Should I close the servlet outputstream? that I don't need to close it, but it's not clear if I need to flush it. Should I expect it from the container as well?
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { byte[] response = getResponse(); String responseType = getResponseType(); response.setContentLength(response.length); response.setContentType(responseType); response.getOutputStream().write(response); response.getOutputStream().flush(); // yes/no/why? }
The flush() method of OutputStream class is used to flush the content of the buffer to the output stream. A buffer is a portion in memory that is used to store a stream of data(characters). That data sometimes will only get sent to an output device, when the buffer is full.
The general rule of them is this: if you opened the stream, then you should close it. If you didn't, you shouldn't. Make sure the code is symmetric. In the case of HttpServletResponse , it's a bit less clear cut, since it's not obvious if calling getOutputStream() is an operation that opens the stream.
No you don't need to close it.
The flush() method will immediately flush the contents of the buffer to the output stream.
You don't need to. The servletcontainer will flush and close it for you. The close by the way already implicitly calls flush.
See also chapter 5.6 of Servlet 3.1 specification:
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.- The amount of content specified in the
setContentLength
orsetContentLengthLong
method of the response has been greater than zero and has been written to the response.- The
sendError
method is called.- The
sendRedirect
method is called.- The
complete
method onAsyncContext
is called.
Calling flush while still running the servlet's service is usually only beneficial when you have multiple writers on the same stream and you want to switch of the writer (e.g. file with mixed binary/character data), or when you want to keep the stream pointer open for an uncertain time (e.g. a logfile).
Guess that the same answer you got in your other question applies here: if it is your stream, flush and close it. Otherwise the stream creator should be doing it, unless otherwise stated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With