public
boolean isAsyncStarted()
Checks
if this request has been put into asynchronous mode. Return true if
this request has been put into asynchronous mode, false otherwise.
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{ System.out.println("Is Asynchronous mode of the request started " + req.isAsyncStarted()); req.startAsync(); System.out.println("Is Asynchronous mode of the request started " + req.isAsyncStarted()); 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"); System.out.println("Is Asynchronous mode of the request started " + req.isAsyncStarted()); } }
Run
the above servlet like below.
As
you see the console logs, you can observe the below information
messages immediately.
Info:
Is Asynchronous mode of the request started false
Info:
Is Asynchronous mode of the request started true
Info:
Thread http-listener-1(2) started at 1405520809734
Info:
Thread http-listener-1(2) finished at 1405520809737
Info:
Total time taken is 3 Milli Seconds
Info:
Is Asynchronous mode of the request started true
After
10 seconds you can see the response in your browser.
No comments:
Post a Comment