Thread pool that binds tasks for a given ID to the same thread

前端 未结 6 1906
别那么骄傲
别那么骄傲 2020-12-28 17:19

Are there any implementations of a thread pool (in Java) that ensures all tasks for the same logical ID are executed on the same thread?

The logic I\'m after is if t

6条回答
  •  鱼传尺愫
    2020-12-28 17:55

    I had to deal with a similar situation recently.

    I ended up with a design similar to yours. The only difference was that the "current" was a map rather than a set: a map from ID to a queue of Runnables. When the wrapper around task's runnable sees that its ID is present in the map it adds the task's runnable to the ID's queue and returns immediately. Otherwise the ID is added to the map with empty queue and the task is executed.

    When the task is done, the wrapper checks the ID's queue again. If the queue is not empty, the runnable is picked. Otherwise it's removed from the map and we're done.

    I'll leave shutdown and cancelation as an exercise to the reader :)

提交回复
热议问题