ExecutorService that executes tasks sequentially but takes threads from a pool

后端 未结 6 1679
孤城傲影
孤城傲影 2021-02-20 11:22

I am trying to build an implementation of the ExecutorService, let\'s call it SequentialPooledExecutor, with the following properties.

6条回答
  •  [愿得一人]
    2021-02-20 11:39

    @Nicolas's answer is probably your best bet as it is simple, well tested, and efficient.

    If however it can not meet your requirement, I would do it like so :

    1. Do not make "SequentialPooledExecutor" an executor service, make it a facade for a "pool" of single thread executor services
    2. Make your "SequentialPooledExecutor" implement a submit method (takes a Runnable / Callable, and a String that represents a "queue name"), returns a Future, like an executor service
    3. On call of this method, make your "SequentialPooledExecutor" dispatch to one of its internal, single thread, executor service, by taking the hash of the queue name, and dispatching it to the corresponding internal executor.

    The hashing part that takes place at step 3 allows you to have the tasks for each "queue name" always go to the same (single thread) executor service inside of your "SequentialPooledExecutor".

    Another possible route is the use of CompletionStage and CompletableFutures. These are, in effect, listenable futures (that have a completion handler). With these, the first time you have a "session", you create a CompletableFuture with your first task, and hold on to it. At each new task, you combine the previous future with the new task, calling thenAcceptAsync (or any of the like). What you get is a linear chain of execution tasks.

提交回复
热议问题