异步 Servlet和 Java EE并发应用

13-06-09 banq
         

Servlet 3.0. ServletRequest#startAsync引入异步,可以将一个请求放入一个异步模型,见下面代码

Servlet 3.1, JSR 340 规范包括异步,除了Servlet 3,1, 并发应用也被导入Java EE 7 的JSR 236,JSR 236提供一个在JavaEE容器中可移植的访问和管理线程池和 ExecutorService的途径:

javax.enterprise.concurrent.ManagedThreadFactory#newThread

ManagedThreadFactory可使用JNDI资源查找获得。

Asynchronous Servlet and Java EE Concurrency Utilities | Java.net举例了说明如下:

@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();
    }
}
<p>

不同于ManagedThreadFactory直接方式,下面两个方式也可以通过JNDI资源查找获得。

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

@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);
    }
}
<p>

Servlet 3.1 和 Java EE 1.0的并发应用Concurrency Utilities 已经在GlassFish 4.0.中可用。

[该贴被banq于2013-06-09 19:24修改过]

[该贴被banq于2013-06-09 19:25修改过]

         

lostalien
2013-06-11 15:20

Servlet 3.1 和 Java EE 1.0的并发应用Concurrency Utilities 已经在GlassFish 4.0.中可用。

1.0?