Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Map/Reduce with Groovy++
ForkJoinPool fjPool = []
def res = fjPool.map(2..<15){ arg ->
// We are in AsyncTaskWithArg<Integer,Integer>
// function which take Integer param and calculate Integer
// both types are type inferenced
//
// method map will fork copy of the task for each element of given Iterable ( 2..<15 Range in this case)
// and when all results ready will merge them in to List<Integer>
// The task itself (the one applied to each element) uses fork/join (which is stupid for Fibonacci)
// For small numbers we just set resut
if(arg <= 1 ) {
// set result of subtask and return null (no merge needed)
return complete(1)
}
// clone two copies of itself and start running concurrently with new arguments
def f1 = fork(arg-1)
def f2 = fork(arg-2)
// what we return is merge function to be called when all subtasks are completed
return {
Integer r1 = f1.join(),
r2 = f2.join()
r1 + r2
}
}
assert res == [2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment