Java Reference
In-Depth Information
In Servlet 3.0, AsyncContext was introduced to represent an execution context for an asynchronous operation
that is initiated on a servlet request. to use the asynchronous context, a servlet should be annotated as @WebServlet ,
and the asyncSupported attribute of the annotation must be set to true . the @WebFilter annotation also contains the
asyncSupported attribute.
Let's take a look at how to perform a nonblocking read. After a listener has been registered
with a ServletInputStream , the status of a nonblocking read can be checked by calling the methods
ServletInputStream.isReady and ServletInputStream.isFinished . For instance, a read can begin once
the ServletInputStream.isReady method returns a true , as shown here:
while (is.isReady() && (b = != -1)) {
len =;
String data = new String(b, 0, len);
To create a ReadListener or WriteListener , three methods must be overridden: onDataAvailable ,
onAllDataRead , and onError . The onDataAvailable method is invoked when data is available to be read or
written, onAllDataRead is invoked once all the data has been read or written, and onError is invoked if an error is
encountered. The following code demonstrates one way to implement the ReadListener interface. You can view these
sources in the file.
package org.javaee7.chapter01;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.AsyncContext;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
public class ReadListenerImpl implements ReadListener {
private ServletInputStream is = null;
private AsyncContext context = null;
public ReadListenerImpl(ServletInputStream in, AsyncContext ac) { = is;
this.context = ac;
public void onDataAvailable() {
try {
StringBuilder sb = new StringBuilder();
int len = -1;
byte b[] = new byte[1024];
Search WWH ::

Custom Search