ichfarbstift ichfarbstift - 1 year ago 79
Java Question

ExecutorService that executes tasks sequentially but takes threads from a pool

I am trying to build an implementation of the

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

  1. All instances of
    share the same thread pool

  2. Calls on the same instance of
    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
myself, but I am wondering if I am reinventing the wheel. I looked into different implementations of
, for example those that are provided by the
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?


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
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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download