title: Impossible to make a cached thread pool with a size limit?
body: <p>It seems to be impossible to make a cached thread pool with a limit to the number of threads that it can create.</p>
  <p>Here is how static <code>Executors.newCachedThreadPool</code> is implemented in the standard Java library:</p>
  <pre><code> public static ExecutorService newCachedThreadPool() {
      return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                    60L, TimeUnit.SECONDS,
                                    new SynchronousQueue&lt;Runnable&gt;());
  }
  </code></pre>
  <p>So, using that template to go on to create a fixed sized cached thread pool:</p>
  <pre><code>new ThreadPoolExecutor(0, 3, 60L, TimeUnit.SECONDS, new SynchronusQueue&lt;Runable&gt;());
  </code></pre>
  <p>Now if you use this and submit 3 tasks, everything will be fine.  Submitting any further tasks will result in rejected execution exceptions.</p>
  <p>Trying this:</p>
  <pre><code>new ThreadPoolExecutor(0, 3, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue&lt;Runable&gt;());
  </code></pre>
  <p>Will result in all threads executing sequentially.  I.e., the thread pool will never make more than one thread to handle your tasks.</p>
  <p>This is a bug in the execute method of <code>ThreadPoolExecutor</code>?  Or maybe this is intentional?  Or there is some other way?</p>
  <p>Edit: I want something exactly like the cached thread pool (it creates threads on demand and then kills them after some timeout) but with a limit on the number of threads that it can create and the ability to continue to queue additional tasks once it has hit its thread limit.  According to sjlee's response this is impossible.  Looking at the <code>execute()</code> method of <code>ThreadPoolExecutor</code> it is indeed impossible.  I would need to subclass <code>ThreadPoolExecutor</code> and override <code>execute()</code> somewhat like <code>SwingWorker</code> does, but what <code>SwingWorker</code> does in its <code>execute()</code> is a complete hack.</p>