package com.chinamobile.epic.tako.common.graphite.query.sync.impl;
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;
public class GraphiteQueryTask extends RecursiveTask<List<String>> {
private List<String> uuids;
private int THRESHOLD = 12;
public GraphiteQueryTask(List<String> uuids) {
this.uuids = uuids;
}
public static void main(String[] args) {
ForkJoinPool pool = ForkJoinPool.commonPool();
List<String> uuids = Lists.newArrayList();
for (int i = 0; i < 45; i++) {
uuids.add("uuid-" + i);
}
List<String> result = pool.invoke(new GraphiteQueryTask(uuids));
System.out.println("========== 结果 ============");
System.out.println(result);
}
@Override
protected List<String> compute() {
List<String> result = Lists.newArrayList();
Collection<GraphiteQueryTask> forks = Lists.newArrayList();
if (uuids.size() > THRESHOLD) {
int mid = uuids.size() >>> 1;
GraphiteQueryTask firstTask = new GraphiteQueryTask(Lists.newArrayList(uuids.subList(0, mid)));
GraphiteQueryTask secondTask = new GraphiteQueryTask(Lists.newArrayList(uuids.subList(mid, uuids.size())));
forks = ForkJoinTask.invokeAll(Arrays.asList(firstTask, secondTask));
} else {
result.add(postGraphite(uuids));
}
for (RecursiveTask<List<String>> task : forks) {
result.addAll(task.join());
}
return result;
}
private String postGraphite(List<String> uuids) {
System.out.println("============>ThreadId: [" + Thread.currentThread().getId() + "] , uuids.size:[" + uuids.size() + "]");
System.out.println(uuids);
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "@@@-" + Thread.currentThread().getId() + "-" + uuids.size();
}
}
转载请标明出处:http://www.cnblogs.com/ssslinppp/