Java Reference
In-Depth Information
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
final AsyncContext asyncContext = req.startAsync();
final PrintWriter writer = res.getWriter();
Thread thread = factory.newThread(new Runnable() {
@Override
public void run() {
writer.println("Complete!");
asyncContext.complete();
}
});
thread.start();
}
}
This example creates a new thread that hosts the time‐consuming process and i nally calls a
complete function from asyncContext . ManagedThreadFactory serves as an available thread from
the pool that you need to start explicitly.
Another approach is to submit the asynchronous runnable to ManagedExecutorService instead
of creating and starting the thread in the servlet. Delegating threading issues to ExecutorService
provides cleaner code, as you'll see in Listing 9‐5.
LISTING 9‐5: An example that delegates to the ExecutorService
package com.devchronicles.asynchronous;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet(urlPatterns="/async", asyncSupported=true)
public class AsyncServlet extends HttpServlet {
@Resource
private ManagedExecutorService executor;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
final AsyncContext asyncContext = req.startAsync();
final PrintWriter writer = res.getWriter();
executor.submit(new Runnable() {
@Override
continues
Search WWH ::




Custom Search