|
1 | 1 | package org.baeldung.java.streams; |
2 | 2 |
|
3 | | -import static org.junit.Assert.*; |
| 3 | +import static org.junit.Assert.assertEquals; |
| 4 | +import static org.junit.Assert.assertTrue; |
4 | 5 |
|
5 | 6 | import java.util.ArrayList; |
6 | 7 | import java.util.List; |
|
9 | 10 | import java.util.stream.Stream; |
10 | 11 |
|
11 | 12 | import org.junit.Test; |
12 | | -import org.slf4j.Logger; |
13 | | -import org.slf4j.LoggerFactory; |
14 | 13 |
|
15 | 14 | public class ThreadPoolInParallelStream { |
16 | | - Integer total = 1784293664; |
17 | | - Logger log = LoggerFactory.getLogger(ThreadPoolInParallelStream.class); |
18 | 15 |
|
19 | 16 | @Test |
20 | | - public void givenListOfInteger_calculateSumOfIntegers() throws InterruptedException, ExecutionException { |
| 17 | + public void giveRangeOfInts_whenSumedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException { |
21 | 18 | List<Integer> aList = new ArrayList<>(); |
22 | | - int listSize = 1_000_000; |
23 | | - for(int i = 1; i <= listSize; i++){ |
| 19 | + int lastNum = 1_000_000; |
| 20 | + int firstNum = 1; |
| 21 | + |
| 22 | + int expectedTotal = (lastNum - firstNum + 1) * (firstNum + lastNum ) / 2; |
| 23 | + |
| 24 | + for(int i = firstNum; i <= lastNum; i++){ |
24 | 25 | aList.add(i); |
25 | | - } |
26 | | - ForkJoinPool customThreadPool = new ForkJoinPool(5); |
27 | | - Integer sum = customThreadPool.submit(() -> aList.parallelStream().reduce( |
| 26 | + } |
| 27 | + |
| 28 | + ForkJoinPool customThreadPool = new ForkJoinPool(4); |
| 29 | + int actualTotal = customThreadPool.submit(() -> aList.parallelStream().reduce( |
28 | 30 | 0, (x, y) -> { |
29 | 31 | return x + y; |
30 | 32 | })).get(); |
31 | 33 |
|
32 | | - assertEquals(total, sum); |
| 34 | + assertEquals(expectedTotal, actualTotal); |
33 | 35 | } |
34 | 36 |
|
35 | 37 | @Test |
|
0 commit comments