In this section, you will learn about initializing AsyncContext using startAsync method.
Let us first familiar about this method :
AsyncContext startAsync() throws java.lang.IllegalStateException
This function was introduced with Servlet 3.0.
It sets the called request into asynchronous mode and instantiates its AsyncContext with the unwrapped ServletRequest and ServletResponse objects. It returns the (re)initialized AsyncContext.
Due to this method calling, it delays the related response until until AsyncContext#complete is called on the returned AsyncContext. This delay also ends if the asynchronous operation has timed out.
It throws IllegalStateException, if asynchronous operations are not support by the Servlet or if the called request is within a filter's scope.
Need of AsyncContext & startAsync() method
Often during handling request, your application thread is waiting for some external resource due to which it become idle for some time. Due to this, you are engaging the thread and therefore a lot of memory is occupied by you without doing any function.
Consider a situation where your application is providing the downloading of files with limited output. In this case, your threads are idle most of the time since they are awaiting to send next bundle of data. Prior to Servlet 3.0 , you couldn't attend/process more than your HTTP thread limit.
With Servlet 3.0, you can attend/ process thousands of connections concurrently which is much more than thread limit. It means you can connect to thousands of client with few HTTP threads.
Method startAsync() doesn't create any thread. Means it will not create new thread for every async request. It just tells the Servlet container do not close this request until in tell you to do so.
Consider a scenario where we have three Servlets - X , Y and Z which have URLs : /x , /y & /z :
Within Servlet X, we have :
Within Servlet Y, we have :
Within Servlet Z, we have following two statements :
request.startAsync().dispatch(); // to /y
request.startAsync(request, response).dispatch(); // to /z
Ask Questions? Discuss: ServletRequest Interface startAsync method
Post your Comment
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.