I need to perform some tasks(Mostly Call multiple External URL's with request parameters and read data) concurrently in java servlet and send response to user within a few seconds.I am trying to use ExecutorService to achieve the same. I need four FutureTasks created in each user request in the doGet method. Each Task runs for around 5-10 sec and the total response time to the user is around 15 sec.
Can you please suggest which of the following design is better while using ExecutorService in a Java servlet?
1)(Creating newFixedThreadPool per request and shutting it down ASAP)
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) (Creating newFixedThreadPool during Servlet Init and shutting it down on servlet destroy)
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) (Creating newCachedThreadPool during Servlet Init and shutting it down on servlet destroy)
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();
}
}