Res.flushBuffer () vs res.getOutputStream (). flush ();

What is the difference between calls:

res.flushBuffer(); 

vs

 res.getOutputStream().flush(); 

Do these methods hold the same buffer?

If so, can you let me know how this buffer is managed by the servlet container?

+4
source share
2 answers

They will clear the same buffer if you used getOutputStream to write to the body. Another alternative is getWriter for non-binary data. If you used this, then call res.getOutputStream().flush(); probably won't work.

The buffer management method is implementation specific, but one of the Tomcat implementations, for example . You can see that there are fields like this:

 /** * The associated output buffer. */ protected OutputBuffer outputBuffer; /** * The associated output stream. */ protected CoyoteOutputStream outputStream; /** * The associated writer. */ protected CoyoteWriter writer; 

Calling getOutputStream() creates a CoyoteOutputStream that uses the outputBuffer field that is shown there, as well as for getWriter() . Therefore, both of them will use outputBuffer depending on what you use. flushBuffer just does this:

 @Override public void flushBuffer() throws IOException { outputBuffer.flush(); } 
+2
source

What is the difference between calls ...

The only significant difference is that the first version will work regardless of whether you are writing / going to write the body in text or binary mode, while the second version only works with binary mode output.

Do these methods hold the same buffer?

Since javadocs do not give an explicit answer, technically it is implementation dependent. However, in practice, the answer is probably โ€œYESโ€ for most implementations, because it is difficult to understand that it makes sense to have separate buffers.

There are some indirect evidence in javadoc:

  • javadoc for setBufferSize(int) says: "Sets the preferred buffer size for the response body." It is understood that this buffer is the same โ€œbufferโ€ referred to in javadoc for flushBuffer() .

  • javadoc for flushBuffer() says: "A call to this method automatically passes a response, which means a status code and headers will be written" ...., which is consistent with the model, where there is one buffer for everything.

Another thing to note is that the response object that the servlet sees can actually be an application-specific wrapper that has been added further to the filter chain. Such a shell may behave in a way that does not match what javadoc (and the rest of the servlet specification) says.


If so, can you let me know how this buffer is managed by the servlet container?

Itโ€™s best to look at the source code of the container.

+1
source

Source: https://habr.com/ru/post/1445169/


All Articles