Class WorkerGroup

java.lang.Object
org.cojen.tupl.util.WorkerGroup

public abstract class WorkerGroup extends Object
A group of workers for running tasks. This class isn't thread safe for enqueuing tasks, and so the caller must provide its own mutual exclusion to protect against concurrent enqueues.

Although this class behaves somewhat like a general purpose thread pool, the actual behavior is different. When adding tasks into a thread pool, any thread can be selected for running the task. A WorkerGroup is best used for managing collections of tasks which must run on the same thread, and in a specific order. When using a general purpose thread pool, these tasks would need to synchronize with each other, leading to contention.

When using a WorkerGroup, the first task in the collection should be enqueued as normal, but all of the remaining tasks should be enqueued directly into the selected worker. This ensures that one thread will run the tasks, and in the correct order. Worker threads are shared among many task collections, and execution is interleaved. Care must be taken to avoid creating stalled tasks, since this can stall the execution of unrelated tasks.

  • Method Details

    • make

      public static WorkerGroup make(int workerCount, int maxSize, long keepAliveTime, TimeUnit unit, ThreadFactory threadFactory)
      Parameters:
      workerCount - number of workers
      maxSize - maximum amount of tasks which can be enqueued per worker
      keepAliveTime - maximum idle time before worker threads exit
      unit - keepAliveTime time unit per worker
      threadFactory - null for default
    • tryEnqueue

      public abstract Worker tryEnqueue(Worker.Task task)
      Attempts to select an available worker and enqueues a task without blocking. When the task object is enqueued, it must not be used again for any other tasks.
      Returns:
      selected worker or null if all worker queues are full and task wasn't enqueued
    • enqueue

      public abstract Worker enqueue(Worker.Task task)
      Enqueue a task, blocking if necessary until space is available. When the task object is enqueued, it must not be used again for any other tasks.
      Returns:
      selected worker
    • join

      public abstract void join(boolean interrupt)
      Waits until all the worker queues are drained. If the worker threads are interrupted and exit, new threads are started when new tasks are enqueued. The same mutual exclusion rules for enqueueing apply to this method too.
      Parameters:
      interrupt - pass true to interrupt the worker threads so that they exit
    • interrupt

      public abstract void interrupt()
      Interrupts all the workers.