Class WorkerGroup
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 Summary
Modifier and TypeMethodDescriptionabstract Worker
enqueue
(Worker.Task task) Enqueue a task, blocking if necessary until space is available.abstract void
Interrupts all the workers.abstract void
join
(boolean interrupt) Waits until all the worker queues are drained.static WorkerGroup
make
(int workerCount, int maxSize, long keepAliveTime, TimeUnit unit, ThreadFactory threadFactory) abstract Worker
tryEnqueue
(Worker.Task task) Attempts to select an available worker and enqueues a task without blocking.
-
Method Details
-
make
public static WorkerGroup make(int workerCount, int maxSize, long keepAliveTime, TimeUnit unit, ThreadFactory threadFactory) - Parameters:
workerCount
- number of workersmaxSize
- maximum amount of tasks which can be enqueued per workerkeepAliveTime
- maximum idle time before worker threads exitunit
- keepAliveTime time unit per workerthreadFactory
- null for default
-
tryEnqueue
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
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.
-