title: ExecutorService, standard way to avoid to task queue getting too full
body: <p>I am using <code>ExecutorService</code> for ease of concurrent multithreaded program. Take following code:</p>
  
  <pre><code>while(xxx) {
      ExecutorService exService = Executors.newFixedThreadPool(NUMBER_THREADS);
      ...  
      Future&lt;..&gt; ... = exService.submit(..);
      ...
  }
  </code></pre>
  
  <p>
  </p>
  
  <p>In my case the problem is that <code>submit()</code> is not blocking if all <code>NUMBER_THREADS</code> are occupied. The consequence is that the Task queue is getting flooded by many tasks. The consequence of this is, that shutting down the execution service with <code>ExecutorService.shutdown()</code> takes ages (<code>ExecutorService.isTerminated()</code> will be false for long time). Reason is that the task queue is still quite full.</p>
  
  <p>For now my workaround is to work with semaphores to disallow to have to many entries inside the task queue of <code>ExecutorService</code>:</p>
  
  <pre><code>...
  Semaphore semaphore=new Semaphore(NUMBER_THREADS);
  
  while(xxx) {
      ExecutorService exService = Executors.newFixedThreadPool(NUMBER_THREADS); 
      ...
      semaphore.aquire();  
      // internally the task calls a finish callback, which invokes semaphore.release()
      // -&gt; now another task is added to queue
      Future&lt;..&gt; ... = exService.submit(..); 
      ...
  }
  </code></pre>
  
  <p>
  </p>
  
  <p>I am sure there is a better more encapsulated solution?</p>