title: Java - HttpServlet: When is the response sent to the client?
body: <p>I was little experimenting with some HttpServlet stuff to understand it better. I wanted to build the scenario that a request is incoming and I need to send the response accordingly and as fast as possible and to do later some more work within the servlet. From my current understanding, the response should only be send to the client when the doGet or doPost method was returned. But from my example, the response is already sent back to the client within the processing of the commands in the servlet. So it is already returned when I was not expecting it to be.</p>
  
  <pre><code>protected void processRequest(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
          try {
              Thread.sleep(500);
          } catch (InterruptedException ex) {
              Logger.getLogger(DisplayHeader.class.getName()).log(Level.SEVERE, null, ex);
          }
  
          response.setContentType("text/plain; charset=ISO-8859-1");
          response.setStatus(HttpServletResponse.SC_FORBIDDEN);
          final StringWriter sw = new StringWriter();
          PrintWriter out = new PrintWriter(sw);
          //TODO most be implemented SynchronizedStatusCodeDimo
          out.println("StatusCode=0");
          out.println("StatusText=Accepted");
          out.println("paymentType=PaymentXY");
          out = response.getWriter();
          out.print(sw.toString());
          out.flush();
          out.close();
  
          try {
              Thread.sleep(1000);
          } catch (InterruptedException ex) {
              Logger.getLogger(DisplayHeader.class.getName()).log(Level.SEVERE, null, ex);
          } }
  </code></pre>
  
  <p>What is happening here, via Firebug I see that I already received the response generated after    510ms. I thought I would need more then 1500ms because of the sleeps. My understanding was based on this post here: <a href="https://stackoverflow.com/questions/2367650/finishing-a-httpservletresponse-but-continue-processing">Link</a></p>