Monday, 4 August 2014

startAsync() : Puts this request into asynchronous mode

public AsyncContext startAsync() throws IllegalStateException
Puts this request into asynchronous mode, and initializes its AsyncContext with the original ServletRequest and ServletResponse objects. Response will be delayed until you call 'complete()' method of AsyncContext.

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{
        final AsyncContext acontext = req.startAsync();
            
        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.







 
Prevoius                                                 Next                                                 Home

No comments:

Post a Comment