This discussion is archived
1 Reply Latest reply: May 1, 2012 7:06 AM by gimbal2 RSS

Thread.sleep in Servlet

878074 Newbie
Currently Being Moderated
Hi,

I have a simple servlet with doGet() as following :

protected void doGet(HttpServletRequest req, HttpServletResponse resp)      throws ServletException, IOException
     {
          PrintWriter pw = resp.getWriter();
          
          pw.write("1");
          pw.flush();
          
          try
          {
               Thread.sleep(10000);
          }
          catch (InterruptedException e)
          {
               // TODO Auto-generated catch block
               e.printStackTrace();
          }
          
          pw.write("2");
          pw.flush();
     }

What I am expecting is as follows :
- client gets '1' on browser
- after wait of 10 seconds
- it flushes '2' to client

And this is what I am getting :
- After making request, it doesn't print '1', rather it waits for 10 sec
- after 10 sec it writes '12'

Why ? if I am calling flush after '1', then shouldn't it print '1' and then sleep before it prints '2' ?

Edited by: Summer on May 1, 2012 5:25 PM
  • 1. Re: Thread.sleep in Servlet
    gimbal2 Guru
    Currently Being Moderated
    not necessarily. Writer.flush() only flushes anything that might be buffered by that writer; it does not have to flush the actual response.

    ServletResponse.flushBuffer() does that. So to properly force flush content to the browser, you would do:
    PrintWriter pw = resp.getWriter();
    
    pw.write("1");
    pw.flush();
    resp.flushBuffer();
    // etc.
    And use \
     tags to format your code. This not only makes it more readable, it prevents the forum from trying to interpret formatting characters.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points