With traditional IO if streamed data is slower than the server can read then the server thread is waiting for that data
public class BlockingIoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
ServletInputStream input = request.getInputStream();
byte[] b = new byte[1024];
int len = -1;
while ((len = input.read(b)) != -1) {
. . .
}
}
}
Servlet 3.1 enhancements
ServletInputStream has the ability to regiser a ReadListener
AsyncContext context = request.startAsync();
ServletInputStream input = request.getInputStream();
input.setReadListener(new MyReadListener(input, context));
ServletOutputStream has the ability to regiser a WriteListener
AsyncContext context = request.startAsync();
ServletOutputStream responeOutput = response.getOutputStream();
responeOutput.setWriteListener(new WriteListener() {
@Override
public void onWritePossible() throws IOException {
while (responeOutput.isReady()) {
// write
}
}
@Override
public void onError(Throwable t) {
// Error handling
context.complete();
}
});