gpt4 book ai didi

java - ServletContextListener : Isn't this incorrect usage?

转载 作者:行者123 更新时间:2023-12-02 07:09:44 28 4
gpt4 key购买 nike

我正在阅读有关“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)”循环。

  1. 根据我的理解,这个上下文监听器线程永远不会退出“contextInitialized()”方法。对吗?
  2. 我的应用程序中的任何其他 Servlet 会发生什么情况?他们可以免费满足请求吗?或者这会导致整个 servlet 容器崩溃吗?

最佳答案

1)我将更改代码如下:

@WebServletContextListener
public class SlowWebService implements ServletContextListener, Runnable {
private volatile boolean running;
ExecutorService executor;
Thread runner;
Queue<AsyncContext> jobQueue;

public void contextInitialized(ServletContextEvent sce) {
jobQueue = new ConcurrentLinkedQueue<AsyncContext>();
sce.getServletContext().setAttribute("slowWebServiceJobQueue", jobQueue);
// pool size matching Web services capacity
executor = Executors.newFixedThreadPool(10);
runner = new Thread(this);
runner.start();
}

public void run() {
running = true;
while(running)
{
try {
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");
}
});
}
}
catch (InterruptException e) {
}
}
}

public void contextDestroyed(ServletContextEvent sce) {
running = false;
runner.interrupt();
executor.shutdown();
}
}

2) 其他 Servlet 只要具有不同的 urlPattern,就不会受到影响。

关于java - ServletContextListener : Isn't this incorrect usage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15666155/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com