public
AsyncContext getAsyncContext()
Gets
the AsyncContext that was created or reinitialized by the most recent
invocation of startAsync() or
startAsync(ServletRequest,ServletResponse) on this request.
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.AsyncContext; @WebServlet(urlPatterns = {"/ProcessRequest"}, asyncSupported=true) public class ProcessRequest extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse res)throws IOException, ServletException{ req.startAsync(); final AsyncContext acontext = req.getAsyncContext(); String threadName = Thread.currentThread().getName(); long startTime = System.currentTimeMillis(); System.out.println("Thread " + threadName + " started at " + startTime); acontext.start(new Runnable() { public void run() { String time = req.getParameter("time"); int wait = Integer.parseInt(time); try{ Thread.sleep(wait); } catch(InterruptedException e){ } HttpServletResponse response = (HttpServletResponse)acontext.getResponse(); try(PrintWriter out = response.getWriter()) { out.println("I am done"); } catch(Exception e){ } acontext.complete(); } }); long endTime = System.currentTimeMillis(); System.out.println("Thread " + threadName + " finished at " + endTime); System.out.println("Total time taken is " +(endTime-startTime) + " Milli Seconds"); } }
Run
the above servlet like below.
As
you see the console logs, you can observe the below information
messages immediately.
Info:
Thread http-listener-1(5) started at 1405140693455
Info:
Thread http-listener-1(5) finished at 1405140693456
Info:
Total time taken is 1 Milli Seconds
After
10 seconds you can see the response in your browser.
No comments:
Post a Comment