ichfarbstift ichfarbstift - 1 month ago 12
Java Question

ExecutorService that executes tasks sequentially but takes threads from a pool

I am trying to build an implementation of the

ExecutorService
, let's call it
SequentialPooledExecutor
, with the following properties.


  1. All instances of
    SequentialPooledExecutor
    share the same thread pool

  2. Calls on the same instance of
    SequentialPooledExecutor
    are executed sequentially.



In other words, the instance waits for the termination of the currently executing task before start processing the next task in its queue.

I am currently in the process of implementing the
SequentialPooledExecutor
myself, but I am wondering if I am reinventing the wheel. I looked into different implementations of
ExecutorService
, for example those that are provided by the
Executors
class, but I did not find one that meets my requirements.

Do you know whether there are existing implementations that I am missing, or should I continue with implementing interface myself?

EDIT:

I think my requirement are not very clear, let's see if I can explain it with other words.

Suppose I have a series of sessions, say 1000 of them (the things that I was calling instance of the executor before). I can submit tasks to a session and I want the guarantee that all tasks that are submitted to the same session are executed sequentially. However, tasks that belong to different sessions should have no dependency from each other.

I want to define an
ExecutorService
that executes these tasks, but uses a bounded number of threads, let's say 200, but ensures that a task is not started before the previous one in the same session is finished.

I don't know if there is anything existing that already does that, or if I should implement such an
ExecutorService
myself.

Answer

If you want to execute your task sequentially simply create a ExecutorService with only one thread thanks to Executors.newSingleThreadExecutor().

If you have different type of tasks and you want to execute only the tasks of the same type sequentially, you can use the same single threaded ExecutorService for the same type of tasks, no need to reinvent the wheel.

So let's say that you have 1 000 different type of tasks, you could use 200 single threaded ExecutorService, the only thing that you need to implement yourself is the fact that you always need to use the same single threaded ExecutorService for a given type of task.