Last active
June 30, 2020 15:32
-
-
Save thatwist/05c137a36a476c86296eabf28a65d5ab to your computer and use it in GitHub Desktop.
Simple ForkJoin program on Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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