Ensuring task execution order in threadpool

后端 未结 17 948
情深已故
情深已故 2020-12-12 11:54

I have been reading about the thread-pool pattern and I can\'t seem to find the usual solution for the following problem.

I sometimes want tasks to be executed serial

17条回答
  •  一整个雨季
    2020-12-12 12:52

    If I understand the problem correctly, the jdk executors don't have this capability but it's easy to roll your own. You basically need

    • a pool of worker threads, each of which has a dedicated queue
    • some abstraction over those queues to which you offer work (c.f. the ExecutorService)
    • some algorithm that deterministically selects a specific queue for each piece of work
    • each piece of work then gets offers to the right queue and hence gets processed in the right order

    The difference to the jdk executors is that they have 1 queue with n threads but you want n queues and m threads (where n may or may not equal m)

    * edit after reading that each task has a key *

    In a bit more detail

    • write some code that transforms a key into an index (an int) in a given range (0-n where n is the number of threads you want), this could be as simple as key.hashCode() % n or it could be some static mapping of known key values to threads or whatever you want
    • at startup
      • create n queues, put them in an indexed structure (array, list whatever)
      • start n threads, each thread just does a blocking take from the queue
      • when it receives some work, it knows how to execute work specific to that task/event (you can obviously have some mapping of tasks to actions if you have heterogenous events)
    • store this behind some facade that accepts the work items
    • when a task arrives, hand it to the facade
      • the facade finds the right queue for the task based on the key, offers it to that queue

    it's easier enough to add auto restarting worker threads to this scheme, you just then need the worker thread to register with some manager to state "I own this queue" and then some housekeeping around that + detection of errors in the thread (which means it unregisters the ownership of that queue returning the queue to a free pool of queues which is a trigger to start a new thread up)

提交回复
热议问题