AsyncContext Interface addListener

In this section, you will learn about addListener method of AsyncContext Interface.

AsyncContext Interface addListener

AsyncContext Interface addListener

In this section, you will learn about addListener method of AsyncContext Interface.

Need of AsyncContext

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.

addListener() method

Syntax of the method is given below:

void addListener(AsyncListener listener)

also,

void addListener(AsyncListener listener, ServletRequest servletRequest, ServletResponse servletResponse)

Parameters:

listener - the AsyncListener to be registered

servletRequest - the ServletRequest that will be included in the AsyncEvent

servletResponse - the ServletResponse that will be included in the AsyncEvent

Description

This method is used to add AsyncListener with the recently created AsyncContext which was initialized using startAsync() method.

This AsyncListener will get the AsyncEvent when asynchronous cycle finishes, results in an error or times out. They(AsyncListener) will be notified in the sequence of creation.

This method throws an IllegalStateException .

How to use ?

The addListener() can be used as follows :


AsyncContext asyncContext = httpServletRequest.startAsync();
AsyncListener myAsyncListener = new AsyncListener() { .... };
asyncContext.addListener(myAsyncListener);