1. Fibonacci
public class Fibonacci extends RecursiveTask<Integer> {
int n;
public Fibonacci(int n) {
this.n = n;
}
@Override
protected Integer compute() {
if (n <= 1) {
return n;
}
Fibonacci f1 = new Fibonacci(n - 1);
f1.fork();
Fibonacci f2 = new Fibonacci(n - 2);
return f2.compute() + f1.join();
}
}
@Test
public void testFibonacci() {
ForkJoinPool forkJoinPool = new ForkJoinPool(4);
Fibonacci fibonacci = new Fibonacci(3);
Assert.assertEquals(forkJoinPool.invoke(fibonacci).longValue(), 2);
}
2. MR
public class MR extends RecursiveTask<Map<String, Long>> {
private String[] fc;
private int start, end;
public MR(String[] fc, int start, int end) {
this.fc = fc;
this.start = start;
this.end = end;
}
@Override
protected Map<String, Long> compute() {
if (end - start == 1) {
return calc(fc[start]);
}
int mid = (start + end) / 2;
MR mr1 = new MR(fc, start, mid);
mr1.fork();
MR mr2 = new MR(fc, mid, end);
return merge(mr2.compute(), mr1.join());
}
private Map<String, Long> merge(Map<String, Long> r1, Map<String, Long> r2){
Map<String, Long> result = new HashMap<>();
result.putAll(r1);
r2.forEach((k,v) -> {
Long c = result.get(k);
if (c != null) {
result.put(k, c+v);
} else {
result.put(k, v);
}
});
return result;
}
private Map<String, Long> calc(String line) {
Map<String, Long> result = new HashMap<>();
String[] words = line.split("\\s+");
for (String w : words) {
result.put(w, result.getOrDefault(w,0L) + 1);
}
return result;
}
}
@Test
public void testWordCount() {
ForkJoinPool forkJoinPool = new ForkJoinPool(4);
String[] fc = {"hello world",
"hello me",
"hello fork",
"hello join",
"fork join in world"};
MR mr = new MR(fc, 0, fc.length);
Map<String, Long> result = forkJoinPool.invoke(mr);
result.forEach((k,v) ->{
System.out.println(k + ":" + v);
});
}