Skip to content

Instantly share code, notes, and snippets.

@jfarcand
Created May 31, 2010 19:42
Show Gist options
  • Save jfarcand/420193 to your computer and use it in GitHub Desktop.
Save jfarcand/420193 to your computer and use it in GitHub Desktop.
@WebServlet(name="AsyncServlet", urlPatterns={"/AsyncServlet"}, asyncSupported=true)
public class AsyncServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
System.out.println("Starting doGet");
AsyncContext ac = request.startAsync();
//<- Why doing that : HttpServletRequest.getAsyncContext()
request.getServletContext().setAttribute("asyncContext", ac);
ac.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");
}
});
System.out.println("Do some stuff in doGet ...");
// Hum, One ScheduledThreadPoolExecutor per request? Also execute will be fire right away...
// might want to put some TimeUnit here and make sure shutdown gets invoked.
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);
executor.execute(new MyAsyncService(ac));
// Two threads may manipulate the same Request/Response objects at the same time, hence this is not
// recommended to manipulate the request after startAsync() gets invoked.
System.out.println("Some more stuff in doGet ...");
} finally {
}
}
class MyAsyncService implements Runnable {
AsyncContext ac;
public MyAsyncService(AsyncContext ac) {
this.ac = ac;
System.out.println("Dispatched to " + "\"MyAsyncService\"");
}
@Override
public void run() {
System.out.println("Some long running process in \"MyAsyncService\"");
ac.complete();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment