Async Servlet not working
developer251 Jan 21, 2014 9:00 AMHi all !
I'd need to use Async Servlet feature on WildFly CR1 to display HTML before a long running process completes. In the following example I'm actually using a Thread.sleep to simulate the long running process, yet the application does not render HTML immediately, so it's working just like any ordinary Synchronous Servlet.
Can you find any mistake in the code or it's a bug of the application server ?
Thanks!
@WebServlet(name="async", urlPatterns={"/async"}, asyncSupported = true )
public class AsyncServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
AsyncContext asyncCtx = request.startAsync();
asyncCtx.addListener(new AsyncListener() {
@Override
public void onComplete(AsyncEvent event) throws IOException {
System.out.println("onComplete");
}
@Override
public void onTimeout(AsyncEvent event) throws IOException {
System.out.println("onTimeout");
}
@Override
public void onError(AsyncEvent event) throws IOException {
System.out.println("onError");
}
@Override
public void onStartAsync(AsyncEvent event) throws IOException {
System.out.println("onStartAsync");
}
});
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);
executor.execute(new MyAsyncService(asyncCtx));
} catch (Exception e) {
e.printStackTrace();
}
PrintWriter writer = response.getWriter();
writer.println("<html>");
// ... prints HTML response here
writer.flush();
}
public class MyAsyncService implements Runnable {
AsyncContext ac;
public MyAsyncService(AsyncContext ac) {
this.ac = ac;
}
@Override
public void run() {
try {
// Simulate long running task
Thread.sleep(20000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ac.complete();
}
}