Refactor ThreadPoolInParallelStream

This commit is contained in:
pivovarit 2017-02-02 07:47:06 +01:00
parent 1a10caefda
commit a312ce5e11
1 changed files with 13 additions and 17 deletions

View File

@ -1,38 +1,34 @@
package org.baeldung.java.streams;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class ThreadPoolInParallelStream {
@Test
public void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal()
throws InterruptedException, ExecutionException {
List<Long> aList = new ArrayList<>();
long lastNum = 1_000_000;
long firstNum = 1;
long expectedTotal = (lastNum + firstNum) * lastNum / 2;
for(long i = firstNum; i <= lastNum; i++){
aList.add(i);
}
long lastNum = 1_000_000;
List<Long> aList = LongStream.range(firstNum, lastNum).boxed()
.collect(Collectors.toList());
ForkJoinPool customThreadPool = new ForkJoinPool(4);
long actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce(
0L, (x, y) -> {
return x + y;
})).get();
long actualTotal = customThreadPool.submit(() -> aList.parallelStream()
.reduce(0L, Long::sum)).get();
assertEquals(expectedTotal, actualTotal);
assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
}
@Test