RESULT
- result typepublic abstract class MergeTree<RESULT>
extends java.lang.Object
This is a base class which is used by its subclasses to create
a pool of worker threads, each executing a task which produces
a result object. The result objects are merged together.
execute(ExecutorService)
creates the thread pool, runs tasks, and returns
the single merged result.
The sequence of merges is determined by the tree, where each node corresponds to the worker thread. The merges are thread safe, i.e., it is guaranteed that only one child node at a time is merging result to the parent node. Eventually, the final result is accumulated at the root node.
To define the worker behaviour, two methods have to be implemented:
runTask()
for the task, and doMerge(Object, Object)
for merging two results together.
getParentIndex(int)
can be overridden to change
the tree structure.Constructor and Description |
---|
MergeTree(int numberOfWorkers)
Creates the merge tree with the given number of worker nodes.
|
Modifier and Type | Method and Description |
---|---|
abstract void |
doMerge(RESULT to,
RESULT from)
Merge one result into another.
|
RESULT |
execute(java.util.concurrent.ExecutorService service)
Runs the workers, merges the results in the tree, and returns the final result.
|
protected int |
getParentIndex(int childIndex)
Returns the index of the parent node for the child node.
|
abstract RESULT |
runTask()
Run single task and get the result.
|
public MergeTree(int numberOfWorkers)
numberOfWorkers
- number of workersprotected int getParentIndex(int childIndex)
childIndex
- index of the child nodepublic RESULT execute(java.util.concurrent.ExecutorService service) throws java.lang.InterruptedException, java.util.concurrent.ExecutionException
service
- the ExecutorService this merge tree will use.java.lang.InterruptedException
- if worker was interruptedjava.util.concurrent.ExecutionException
- if the exception occurred in one of the worker threadspublic abstract RESULT runTask() throws java.lang.Exception
java.lang.Exception
- if the exception occurred while running the task