title: Controlled ThreadPoolExecutor in Java Spring
body: <p>I need to create a global ThreadPoolTaskExecutor in my Spring application which will be responsible for running multi-threaded tasks in my application.</p>
  
  <p>However, for every request I want to limit the number of threads used from that global ThreadPool. How should I ensure that this restriction, per request, is enforced? </p>
  
  <p>For eg.</p>
  
  <p>I create a global thread-pool with max pool size as 50 threads. But I want to limit the number of threads per Request to say 5 threads. But these 5 threads could only be allocated from the 50 threads available in global thread pool defined in Configuration file.</p>
  
  <p>Configuration class for creating the task executor.</p>
  
  <pre><code>@Configuration
  public class ThreadPoolConfiguration {
  
      @Value("${threadpool.corepoolsize}")
      int corePoolSize;
  
      @Value("${threadpool.maxpoolsize}")
      int maxPoolSize;
  
      @Bean
      public ThreadPoolTaskExecutor taskExecutor() {
          ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
          pool.setCorePoolSize(corePoolSize);
          pool.setMaxPoolSize(maxPoolSize);
          pool.setWaitForTasksToCompleteOnShutdown(true);
          return pool;
      }
  }
  </code></pre>
  
  <p>Controller class</p>
  
  <pre><code>@RestController
  public class WebController {
  
      @Autowired
      ThreadPoolTaskExecutor threadPool;
  
      @RequestMapping("/process")
      public String process(){
  
          String msg = "";
          List&lt;Future&lt;String&gt;&gt; futureList = new ArrayList&lt;&gt;();
          for(int threadNumber = 0; threadNumber &lt; 5; threadNumber ++){
              CallableWorker callableTask = new CallableWorker(String.valueOf(threadNumber));
              Future&lt;String&gt; result = threadPool.submit(callableTask);
              futureList.add(result);
          }
  
          for(Future&lt;String&gt; future: futureList){
              try {
                  msg += future.get() + "#####";
              } catch (Exception e){}
          }
  
          return msg;
      }
  }
  </code></pre>
  
  <p>Disclaimer: This is just sample code I got from a <a href="http://javasampleapproach.com/spring-framework/spring-core/spring-threadpooltaskexecutor-callable-interface-concurrency-programming" rel="nofollow noreferrer">blog post</a>.</p>
  
  <p>How can I implement such a design? I don't see any sub thread pool which can be created. Neither do I want to instantiate a thread pool for every request as that would be catastrophic.</p>
  
  <p>Any suggestion?</p>