Controlling Task execution order with ExecutorService

前端 未结 8 1984
一生所求
一生所求 2020-12-02 14:30

I have a process which delegates asynch tasks to a pool of threads. I need to ensure that certain tasks are executed in order. So for example

Tasks arrive in order<

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 15:02

    When I've done this in the past I've usually had the ordering handled by a component which then submits callables/runnables to an Executor.

    Something like.

    • Got a list of tasks to run, some with dependencies
    • Create an Executor and wrap with an ExecutorCompletionService
    • Search all tasks, any with no dependencies, schedule them via the completion service
    • Poll the completion service
    • As each task completes
      • Add it to a "completed" list
      • Reevaluate any waiting tasks wrt to the "completed list" to see if they are "dependency complete". If so schedule them
      • Rinse repeat until all tasks are submitted/completed

    The completion service is a nice way of being able to get the tasks as they complete rather than trying to poll a bunch of Futures. However you will probably want to keep a Map which is populated when a task is schedule via the completion service so that when the completion service gives you a completed Future you can figure out which TaskIdentifier it is.

    If you ever find yourself in a state where tasks are still waiting to run, but nothing is running and nothing can be scheduled then your have a circular dependency problem.

提交回复
热议问题