1
votes

The traditional ThreadPoolExecutor uses a supplied BlockingQueue to queue items only when there are no idle core threads available for the incoming tasks. If there are idle core threads the executor tries to assign the threads directly for the incoming tasks.

I want a slightly different behavior. I want all the tasks to be forcefully submitted to the BlockingQueue and the executor service to poll tasks only from the queue.

I will have my own implementation of the BlockingQueue that will supply items in poll() based on a check (check the business logic passes for processing the tasks), if the check fails the items will not be supplied in poll(). I believe, ThreadPoolExecutor is already implemented with the assumption that poll() returning null need not necessarily mean the queue is empty.

I am aware of an issue with this model. The core threads in the traditional ThreadPoolExecutor are created only when tasks are submitted to the executor through its execute() method. Now if I override execute() method to directly queue tasks to the BlockingQueue, it might not create the Core threads. I can work-around this problem by PreStarting the Core threads and setting it not to Timeout, thus the core threads will always be alive. I also need to make validate that the num core threads is not configured with 0.

Will this model work? Am I missing to handle some case? Your thoughts.

1

1 Answers

1
votes

If I understood you correctly, you will submit tasks to some ThreadPool, but you want to choose if you will really process these tasks depending on some logic? In that case:

  1. Why don't you check if the task is eligible for processing before submitting it to the Executor?
  2. You can always do the check inside the task as first instructions - if check fail then just return from the task - this will give you multithreading for the checking logic.
  3. I don't really see any reason to insist on doing it in the hard and messy way with overriding the Executor, BlockingQueue, preinstantiating threads and possibly other hacks.
  4. It is not responsibility of ThreadPoolExecutor to decide if a submitted task should be executed or not - it is the responsibility of the task submitter, or the task itself could contain such logic to decide to finish early without much processing.