/*
*
find all managers of all departments with an employee
*
older than 65
*/
private static Manager[] find(Corporation c) {
class FinderTask extends RecursiveTask<List<Manager>> {
private final Department[] departments;
private final int from, to;
private final int targetBatchSize = 2;
public FinderTask(Department[] departments,
int from, int to) {
this.departments = departments;
this.from = from;
this.to = to;
}
private List<Manager> findSequentially() {
List<Manager> result = new ArrayList<>();
for
(int i=from;i<to;i++) {
Department
d = departments[i];
for (Employee e : d.getEmployees()) {
if (e.getAge() > 65) {
result.add(d.getManager());
}
}
}
return result;
}
public List<Manager> compute() {
if (to-from < targetBatchSize)
return findSequentially();
int half = (to-from)/2;
FinderTask task1
= new FinderTask(departments,from,from+half);
FinderTask
task2
= new FinderTask(departments,from+half,to);
invokeAll(task1,task2);
try {
List<Manager> result = task1.get();
result.addAll(task2.get());
return result;
} catch (final InterruptedException |
ExecutionException e) {
throw new RuntimeException(e);
}
}
}
Department[] departments
= c.getDepartments().toArray(new Department[0]);
return ForkJoinPool
.commonPool()
.invoke(new FinderTask(departments,0,
departments.length))
.toArray(new Manager[0]);
}
|