ThreadPoolExecutor without a Queue

喜欢而已 提交于 2019-12-13 12:27:01

问题


I want to create a fixed-size thread pool that admits no task into its queue. In other words, if the thread pool is currently in use, the incoming task should be rejected outright. Based on the documentation, one way to do this, in my opinion, would be to create a dummy Queue object which refuses to admit a task. What is the idiomatic way to accomplish this in Java?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/10186397/threadpoolexecutor-without-a-queue

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