ThreadPoolExecutor without a Queue

泪湿孤枕 提交于 2019-12-05 05:37:09

You can use a SynchronousQueue in your ThreadPoolExector which is a queue which holds no objects. The cached thread pool uses this because it creates new threads on demand.

If it cannot be queued but I would suggest using the RejectedExecutionHandler to run the task in the current thread. This way it will always be run "immediately".

BTW: It would be useful to make it clear why you want to do this.

Can you elaborate as to why you want to do such a thing? The fundamental purpose of a TP + Q is to have an automatic "holding mechanism" for work and decouple the workers from the work creation process. If your intent is to only have as many acceptable work packages as workers then you dont really need a TPE.

I want to create a fixed-size thread pool that admits no task into its queue.

For posterity, if you need a thread-pool that does not have a queue and does run all of the jobs (slightly different than the OP), then you can use the SynchronousQueue which will block until a thread is ready for the job. The trick is to use a RejectedExecutionHandler which calls put(...) on the queue which will block.

threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
  unit, new SynchronousQueue<Runnable>(),
  new RejectedExecutionHandler() {
    @Override
    public void rejectedExecution(Runnable runnable, ThreadPoolExecutor executor){
      try {
        // this needs to be put(...) and not add(...)
        executor.getQueue().put(runnable);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
    }
  });

You will be able to submit jobs until the maximumPoolSize number of threads is reached and then the submitting will block until a job finishes and a thread is available to de-queue from the SynchronousQueue.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!