Skip to content

Instantly share code, notes, and snippets.

@feuyeux
Last active March 12, 2019 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feuyeux/4d0ecebe7190b3d6d78bafc53036dfde to your computer and use it in GitHub Desktop.
Save feuyeux/4d0ecebe7190b3d6d78bafc53036dfde to your computer and use it in GitHub Desktop.
test_stream_parallel_forkjoin_threadpool
@Test
public void test() throws InterruptedException, ExecutionException {
ForkJoinPool customThreadPool = new ForkJoinPool(8);
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("pool-%d").build();
ThreadPoolExecutor executor = new ThreadPoolExecutor(5, Integer.MAX_VALUE,
1, TimeUnit.MINUTES,
new LinkedBlockingQueue<>(5),
threadFactory,
new ThreadPoolExecutor.AbortPolicy());
long firstNum = 1;
long lastNum = 30;
Stream<Long> stream = LongStream.rangeClosed(firstNum, lastNum).boxed();
Stream<Long> stream2 = LongStream.rangeClosed(firstNum, lastNum).boxed();
Stream<Long> longStream = stream2.parallel();
executor.submit(() -> {
longStream.forEach(l -> {
System.out.println(Thread.currentThread().getName() + ":" + l + " " + longStream.isParallel());
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException ignored) {}
});
}).get();
long actualTotal = customThreadPool.submit(() -> {
System.out.println(Thread.currentThread().getName() + ":" + stream.isParallel());
return stream.reduce(0L, Long::sum);
}).get();
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
}
@feuyeux
Copy link
Author

feuyeux commented Mar 12, 2019

ForkJoinPool.commonPool-worker-3:5 true
ForkJoinPool.commonPool-worker-2:28 true
ForkJoinPool.commonPool-worker-4:2 true
ForkJoinPool.commonPool-worker-1:10 true
ForkJoinPool.commonPool-worker-6:7 true
pool-0:20 true
ForkJoinPool.commonPool-worker-5:14 true
ForkJoinPool.commonPool-worker-7:9 true
ForkJoinPool.commonPool-worker-2:27 true
ForkJoinPool.commonPool-worker-7:8 true
ForkJoinPool.commonPool-worker-1:11 true
ForkJoinPool.commonPool-worker-3:4 true
ForkJoinPool.commonPool-worker-4:3 true
ForkJoinPool.commonPool-worker-5:15 true
ForkJoinPool.commonPool-worker-6:6 true
pool-0:19 true
ForkJoinPool.commonPool-worker-2:30 true
ForkJoinPool.commonPool-worker-5:29 true
ForkJoinPool.commonPool-worker-1:1 true
ForkJoinPool.commonPool-worker-4:25 true
ForkJoinPool.commonPool-worker-3:13 true
pool-0:22 true
ForkJoinPool.commonPool-worker-6:12 true
ForkJoinPool.commonPool-worker-7:17 true
ForkJoinPool.commonPool-worker-2:21 true
ForkJoinPool.commonPool-worker-4:26 true
ForkJoinPool.commonPool-worker-7:18 true
pool-0:16 true
ForkJoinPool.commonPool-worker-6:23 true
ForkJoinPool.commonPool-worker-3:24 true
ForkJoinPool-1-worker-1:false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment