user191776
user191776

Reputation:

ThreadPoolExecutor without a Queue

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?

Upvotes: 10

Views: 7191

Answers (3)

Gray
Gray

Reputation: 116908

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) {
      if (executor.isShutdown()) {
        throw new RejectedExecutionException("pool already shutdown");
      }
      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.

NOTE: After the thread pool is shutdown any Runnables that are submitted must throw RejectedExecutionException otherwise they will block indefinitely in executor.getQueue().put(...) waiting for an idle thread.

Upvotes: 3

Peter Lawrey
Peter Lawrey

Reputation: 533710

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.

Upvotes: 17

vivekv
vivekv

Reputation: 2298

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.

Upvotes: -1

Related Questions