title: How to decide whether to use newCachedThreadPool or newFixedThreadPool?
body: <p>I am working on a project in which I need to make sure each thread is working on a particular range. For example:</p>
  
  <pre><code>NO_OF_THREADS: 2
  NO_OF_TASKS: 10
  </code></pre>
  
  <p>If <code>number of threads is 2</code> and <code>number of tasks is 10</code> then each thread will be performing <code>10 tasks</code>. So that means 2 thread will be doing <code>20 tasks</code>. </p>
  
  <p><strong>In actual scenario these numbers (number of tasks and number of threads) will be very high as both of them are configurable in my code.</strong></p>
  
  <p>In the above example, <code>first thread</code> should be using id between <code>1 and 10</code> and <code>second thread</code> should be using id between <code>11 and 20</code> and so on if any more threads. And after that each thread will make a database connection and then insert into database. </p>
  
  <p>So I have my below code which is working fine.</p>
  
  <pre><code>public static void main(String[] args) {
  
      final int noOfThreads = 2;
      final int noOfTasks = 10;
  
      //create thread pool with given size 
      ExecutorService service = Executors.newFixedThreadPool(noOfThreads);
  
      // queue some tasks 
      for (int i = 0, int nextId = 1; i &lt; noOfThreads; i++, nextId += noOfTasks) {
          service.submit(new ThreadTask(nextId, noOfTasks));
      }
  }
  
  class ThreadTask implements Runnable {
      private final int id;
      private int noOfTasks;
  
      public ThreadTask(int nextId, int noOfTasks) {
          this.id = nextId;
          this.noOfTasks = noOfTasks;
      }
  
      public void run() {
  
      //make a database connection
  
          for (int i = id; i &lt; id + noOfTasks; i++) {
  
          //insert into database
          }
      }
  }
  </code></pre>
  
  <p><strong>My question:-</strong></p>
  
  <p>I was going through various article on the internet and I read about <code>newCachedThreadPool</code>. So now I am wondering is - Should I use <code>newFixedThreadPool</code> or <code>newCachedThreadPool</code> in my code? As currently I am using <code>nexFixedThreadPool</code>. I am not able to decide on what factors should I choose <code>newCachedThreadPool</code> or <code>newFixedThreadPool</code>. So that is the reason I posted my scenario what I am going to do with my code.</p>
  
  <p>Can anyone help me out what should I be choosing here? And please explain me in details why we are choosing that on what factors so that I can understand this very well. I have already gone through java docs but not able to decide what should I choose here.</p>
  
  <p>Thanks for the help.</p>