Note that there are some explanatory texts on larger screens.

plurals
  1. POExecutorService in Java Servlet
    text
    copied!<p>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.</p> <p>Can you please suggest which of the following design is better while using ExecutorService in a Java servlet?</p> <p><strong>1)(Creating newFixedThreadPool per request and shutting it down ASAP)</strong></p> <pre><code>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(); } } </code></pre> <p><strong>2) (Creating newFixedThreadPool during Servlet Init and shutting it down on servlet destroy)</strong></p> <pre><code>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(); } } </code></pre> <p><strong>3) (Creating newCachedThreadPool during Servlet Init and shutting it down on servlet destroy)</strong></p> <pre><code>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(); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload