Last active
March 12, 2019 12:41
-
-
Save feuyeux/4d0ecebe7190b3d6d78bafc53036dfde to your computer and use it in GitHub Desktop.
test_stream_parallel_forkjoin_threadpool
This file contains hidden or 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
@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); | |
} |
Author
feuyeux
commented
Mar 12, 2019
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment