Asynchronous operation was introduced in Servlet 3.0. ServletRequest#startAsync is used to put the request into asynchronous mode. A thread need to be created implicitly or explicitly (see here for an example). Servlet 3.1, JSR 340 includes clarifications in asynchronous area. Besides Servlet 3,1, Concurreny Utilities for Java EE 1.0, JSR 236 is introduced in Java EE 7. JSR 236 provides a portable way to access managed thread pools and ExecutorService in a Java EE container. In this blog, I will illustrate how to achieve this in a servlet asynchronous environment.

javax.enterprise.concurrent.ManagedThreadFactory#newThread

A ManagedThreadFactory can be accessed through JNDI resource lookup, which can be achieved through the @Resource annotation. A thread can be created from the factory as usual. @WebServlet(urlPatterns="/test", asyncSupported=true) public class TestAsyncMTFServlet extends HttpServlet {     @Resource     private ManagedThreadFactory managedThreadFactory;     @Override     protected void doGet(HttpServletRequest req, HttpServletResponse res)             throws ServletException, IOException {         final AsyncContext asyncContext = req.startAsync();         final PrintWriter writer = res.getWriter();         Runnable runnable = new Runnable() {             @Override             public void run() {                 writer.println("Done");                 asyncContext.complete();             }         };         Thread thread = managedThreadFactory.newThread(runnable);         thread.start();     } }

javax.enterprise.concurrent.ManagedExecutorService#submit, javax.enterprise.concurrent.ManagedScheduledExecutorService#schedule

Instead of accessing thread factory directly, ManagedExecutorService and ManagedScheduledExecutorService are also available through JNDI resource lookup. The following example illustrates the usage of the former. @WebServlet(urlPatterns="/test2", asyncSupported=true) public class TestAsyncMESServlet extends HttpServlet {     @Resource     private ManagedExecutorService managedExecutorService;     @Override     protected void doGet(HttpServletRequest req, HttpServletResponse res)             throws ServletException, IOException {         final AsyncContext asyncContext = req.startAsync();         final PrintWriter writer = res.getWriter();         Runnable runnable = new Runnable() {             @Override             public void run() {                 writer.println("Done");                 asyncContext.complete();             }         };         managedExecutorService.submit(runnable);     } } Servlet 3.1 and Concurrency Utilities for Java EE 1.0 are available in GlassFish 4.0.