Skip to content

Instantly share code, notes, and snippets.

@Quar
Last active January 18, 2018 02:02
Show Gist options
  • Select an option

  • Save Quar/7dfbe63a36344708cc71eb4ff856ddcb to your computer and use it in GitHub Desktop.

Select an option

Save Quar/7dfbe63a36344708cc71eb4ff856ddcb to your computer and use it in GitHub Desktop.
examples of using ForkJoinPool
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class TestForkJoinPool {
static String accumulate(int from, int to, String name) {
int sum = 0;
for (int i = from; i <= to; i++) {
//System.out.println(name + " is accumulating " + i);
sum += i;
}
return String.format(
"%s: sum from %d to %d = %d",
name, from, to, sum);
}
public static void main(String[] args) {
ForkJoinPool pool = new ForkJoinPool(4);
List<ForkJoinTask<String>> tasks = new ArrayList<>();
for (int i = 0; i < 5000; i++) {
int from = i * 100;
int to = from + 100;
String name = "summation" + (i + 1);
tasks.add(
pool.submit( () -> accumulate(from, to, name) )
);
}
List<String> results = tasks.stream().parallel().map(
r -> {
try {
return r.get();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}).collect(Collectors.toList());
results.forEach(System.out::println);
}
}
import java.util.concurrent.{ForkJoinPool, ForkJoinTask}
import java.util.{List, ArrayList}
import java.util.stream.Collectors
import scala.util.Try
object TestForkJoinPool {
def accumulate(from:Int, to:Int, name:String):String = {
var sum = 0
var i = from
while(i <= to) {
//System.out.println(name + " is accumulating " + i);
sum += i
i+=1
}
return s"${name}: sum from ${from} to ${to} = ${sum}"
}
def accumulateTask(i:Int):ForkJoinPool=>ForkJoinTask[String] = {
val from = i * 100
val to = from + 100
val name = s"summation ${i + 1}"
return (pool:ForkJoinPool) => pool.submit{ () => accumulate(from, to, name) }
}
def main(args:Array[String]) {
val pool = new ForkJoinPool(4);
val tasks = (1 until 5000) map { accumulateTask(_)(pool) }
val results = tasks.toStream.map{
r => Try{ r.get() }
}.toList
results.foreach(println);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment