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
servicemethod of the servlet.- The amount of content specified in the
setContentLengthor
setContentLengthLongmethod of the response has been greater than zero and
has been written to the response.- The
sendErrormethod is called.- The
sendRedirectmethod is called.- The
completemethod onAsyncContextis 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).