Created
June 28, 2016 20:50
-
-
Save nipafx/2bf39b728a66ff2e6f14ca89f991d670 to your computer and use it in GitHub Desktop.
Checking in which pool parallel streams are executed
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
package org.codefx.lab.stream; | |
import java.util.concurrent.CountDownLatch; | |
import java.util.concurrent.ForkJoinPool; | |
import java.util.function.Consumer; | |
import java.util.stream.IntStream; | |
public class ParallelStream { | |
public static void main(String[] args) throws InterruptedException { | |
doWithStream(stream -> stream.sum()); | |
doWithStream(stream -> stream.parallel().sum()); | |
doWithStream(stream -> new ForkJoinPool(8).submit(() -> stream.parallel().sum())); | |
} | |
private static void doWithStream(Consumer<IntStream> streamExecutor) throws InterruptedException { | |
CountDownLatch latch = new CountDownLatch(16); | |
streamExecutor.accept( | |
IntStream | |
.range(0, 16) | |
.peek(i -> printThreadName(latch, i)) | |
); | |
latch.await(); | |
System.out.println("Done!\n"); | |
} | |
private static void printThreadName(CountDownLatch latch, int i) { | |
System.out.println(i + ": " + Thread.currentThread().getName()); | |
latch.countDown(); | |
try { | |
Thread.sleep(100); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment