Skip to content

Instantly share code, notes, and snippets.

@ptaylor
Created September 13, 2018 09:46
Show Gist options
  • Save ptaylor/a78150120209d8ffd31a429ab45506a4 to your computer and use it in GitHub Desktop.
Save ptaylor/a78150120209d8ffd31a429ab45506a4 to your computer and use it in GitHub Desktop.
Java 8 parallelStream & ForkJoinPool
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
public class ParallelStreamTest {
private static boolean verbose = false;
private static int size = 50;
private static int sleepTime = 100;
public static void main(String[] args) throws Exception {
try {
stats(ForkJoinPool.commonPool());
List<Long> list0 = LongStream.rangeClosed(1, size).boxed().collect(Collectors.toList());
System.out.println("list0: " + list0);
System.out.println("");
Callable<List<Long>> sequentalTask = () -> list0.stream().map(ParallelStreamTest::calculate).collect(Collectors.toList());
Callable<List<Long>> parallelTask = () -> list0.parallelStream().map(ParallelStreamTest::calculate).collect(Collectors.toList());
System.out.println("SEQUENTAL TASK:");
long before = System.currentTimeMillis();
List<Long> list1 = sequentalTask.call();
System.out.println("elapsedTime: " + (System.currentTimeMillis() - before));
System.out.println("list1: " + list1);
System.out.println("");
System.out.println("PARALLEL TASK:");
before = System.currentTimeMillis();
List<Long> list2 = parallelTask.call();
System.out.println("elapsedTime: " + (System.currentTimeMillis() - before));
System.out.println("list2: " + list2);
System.out.println("");
stats(ForkJoinPool.commonPool());
System.out.println("PARALLEL TASK FORK-JOIN POOL:");
ForkJoinPool threadPool = new ForkJoinPool();
List<Long> list3 = threadPool.submit(parallelTask).get();
System.out.println("elapsedTime: " + (System.currentTimeMillis() - before));
System.out.println("list3: " + list3);
System.out.println("");
stats(threadPool);
System.out.println("SEQUENTAL TASK FORK-JOIN POOL:");
threadPool = new ForkJoinPool();
List<Long> list4 = threadPool.submit(sequentalTask).get();
System.out.println("elapsedTime: " + (System.currentTimeMillis() - before));
System.out.println("list4: " + list4);
System.out.println("");
stats(threadPool);
} catch (Exception e) {
System.out.println("" + e);
}
}
private static long calculate(long l){
try {
if (verbose) System.out.println("[" + Thread.currentThread().getName() + "] " + l);
Thread.sleep(sleepTime);
} catch (InterruptedException e) { /**/ }
return l * 10;
}
private static void stats(ForkJoinPool fjp) {
System.out.println("availableProcessors: " + Runtime.getRuntime().availableProcessors());
System.out.println(fjp.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment