我需要在 java servlet 中同时执行一些任务(主要是使用请求参数调用多个外部 URL 并读取数据)并在几秒钟内向用户发送响应。我正在尝试使用 ExecutorService 来实现相同的目的。我需要在 doGet 方法的每个用户请求中创建四个 FutureTasks。每个任务运行约 5-10 秒,对用户的总响应时间约为 15 秒。
在 Java servlet 中使用 ExecutorService 时,您能否建议以下哪种设计更好?
1)(为每个请求创建 newFixedThreadPool 并尽快将其关闭)
public class MyTestServlet extends HttpServlet
{
ExecutorService myThreadPool = null;
public void init()
{
super.init();
}
protected void doGet(HttpServletRequest request,HttpServletResponse response)
{
myThreadPool = Executors.newFixedThreadPool(4);
taskOne = myThreadPool.submit();
taskTwo = myThreadPool.submit();
taskThree = myThreadPool.submit();
taskFour = myThreadPool.submit();
...
...
taskOne.get();
taskTwo.get();
taskThree.get();
taskFour.get();
...
myThreadPool.shutdown();
}
public void destroy()
{
super.destroy();
}
}
2)(在 Servlet Init 期间创建 newFixedThreadPool 并在 servlet 销毁时将其关闭)
public class MyTestServlet extends HttpServlet
{
ExecutorService myThreadPool = null;
public void init()
{
super.init();
//What should be the value of fixed thread pool so that it can handle multiple user requests without wait???
myThreadPool = Executors.newFixedThreadPool(20);
}
protected void doGet(HttpServletRequest request,HttpServletResponse response)
{
taskOne = myThreadPool.submit();
taskTwo = myThreadPool.submit();
taskThree = myThreadPool.submit();
taskFour = myThreadPool.submit();
...
...
taskOne.get();
taskTwo.get();
taskThree.get();
taskFour.get();
...
}
public void destroy()
{
super.destroy();
myThreadPool.shutdown();
}
}
3)(在 Servlet Init 期间创建 newCachedThreadPool 并在 servlet 销毁时将其关闭)
public class MyTestServlet extends HttpServlet
{
ExecutorService myThreadPool = null;
public void init()
{
super.init();
myThreadPool = Executors.newCachedThreadPool();
}
protected void doGet(HttpServletRequest request,HttpServletResponse response)
{
taskOne = myThreadPool.submit();
taskTwo = myThreadPool.submit();
taskThree = myThreadPool.submit();
taskFour = myThreadPool.submit();
...
...
taskOne.get();
taskTwo.get();
taskThree.get();
taskFour.get();
...
}
public void destroy()
{
super.destroy();
myThreadPool.shutdown();
}
}