【发布时间】:2014-07-24 16:27:54
【问题描述】:
这些天我正在学习 Servlet 3.0 Async Feature,主要思想是将绑定到 Http 线程的任务释放到另一个线程,以便 Http 线程可以回到 Http 线程池(不会阻塞长任务处理),那么你的应用程序可能会更敏感。这里一切顺利。
我找到了两种处理耗时任务的方法
-
acontext.start()
asyncContext.start(new Runnable() { @Override public void run() { serviceImpl(req, resp, adapter, context, isNotLeakScan); } });官方文档说:
acontext.start(new Runnable() {...}) gets a new thread from the container. -
使用 BlockingQueue ,然后新建一个 Tread 来处理队列中的可运行对象。
private static final BlockingQueue queue = new LinkedBlockingQueue(); thread = new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(2000); AsyncContext context; while ((context = queue.poll()) != null) { try { ServletResponse response = context.getResponse(); response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.printf("Thread %s completed the task", Thread.currentThread().getName()); out.flush(); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { context.complete(); } } } catch (InterruptedException e) { return; } }}
我的问题是:
这两种方法有什么区别?
第一个是否处理了对 Tomcat 容器的任务管理(假设我们已经在 Tomcat 上部署了应用)
第二种方式只是显示手动处理任务的方式?
【问题讨论】:
标签: java multithreading tomcat servlets asynchronous