Created
May 31, 2010 19:42
-
-
Save jfarcand/420193 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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