Skip to content

Instantly share code, notes, and snippets.

@thatwist
Last active June 30, 2020 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thatwist/05c137a36a476c86296eabf28a65d5ab to your computer and use it in GitHub Desktop.
Save thatwist/05c137a36a476c86296eabf28a65d5ab to your computer and use it in GitHub Desktop.
Simple ForkJoin program on Java
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.ForkJoinPool;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
public interface Node {
Collection<Node> getChildren();
long getValue();
}
public class Test {
public void test() {
int i = 0;
}
public static void main(String[] args) {
Node root = getRootNode();
new ForkJoinPool().invoke(new ValueSumCounter(root));
}
}
class ValueSumCounter extends RecursiveTask<Long>{
private final Node node;
public ValueSumCounter(Node node) {
this.node = node;
}
@Override
protected Long compute() {
long sum = node.getValue();
List<ValueSumCounter> subTasks = new LinkedList<>();
for(Node child : node.getChildren()) {
ValueSumCounter task = new ValueSumCounter(child);
task.fork();
subTasks.add(task);
}
for(ValueSumCounter task : subTasks) {
sum += task.join();
}
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment