我正在阅读有关“Servlet 3.0 中的异步处理支持”的专家(?)教程(http://www.javaworld.com/javaworld/jw-02-2009/jw-02-servlet3.html?page=2) . 其中有以下代码片段:
@WebServlet(name="myServlet", urlPatterns={"/slowprocess"}, asyncSupported=true)
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
AsyncContext aCtx = request.startAsync(request, response);
ServletContext appScope = request.getServletContext();
((Queue<AsyncContext>)appScope.getAttribute("slowWebServiceJobQueue")).add(aCtx);
}
}
@WebServletContextListener
public class SlowWebService implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
Queue<AsyncContext> jobQueue = new ConcurrentLinkedQueue<AsyncContext>();
sce.getServletContext().setAttribute("slowWebServiceJobQueue", jobQueue);
// pool size matching Web services capacity
Executor executor = Executors.newFixedThreadPool(10);
while(true)
{
if(!jobQueue.isEmpty())
{
final AsyncContext aCtx = jobQueue.poll();
executor.execute(new Runnable(){
public void run() {
ServletRequest request = aCtx.getRequest();
// get parameteres
// invoke a Web service endpoint
// set results
aCtx.forward("/result.jsp");
}
});
}
}
}
public void contextDestroyed(ServletContextEvent sce) {
}
}
因为,这是一篇专家“这是如何完成的”文章,我假设他们不会编写一些愚蠢的代码。但我无法接受在“contextInitialized()”中有一个“while(true)”循环。
- 据我了解,此上下文侦听器线程永远不会退出“contextInitialized()”方法。对 ?
- 我的应用程序中的任何其他 Servlet 会发生什么情况?他们可以免费服务请求吗?或者这是否会降低整个 servlet 容器?