Skip to content

Commit c075627

Browse files
committed
BAEL-612: Example usage of ForkJoinTask
1 parent f36d7f1 commit c075627

2 files changed

Lines changed: 48 additions & 0 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.baeldung.concurrent.future;
2+
3+
import java.util.concurrent.RecursiveTask;
4+
5+
public class FactorialSquareCalculator extends RecursiveTask<Integer> {
6+
private static final long serialVersionUID = 1L;
7+
8+
final private Integer n;
9+
10+
public FactorialSquareCalculator(Integer n) {
11+
this.n = n;
12+
}
13+
14+
@Override
15+
protected Integer compute() {
16+
if (n <= 1) {
17+
return n;
18+
}
19+
20+
FactorialSquareCalculator calculator = new FactorialSquareCalculator(n - 1);
21+
22+
calculator.fork();
23+
24+
return n * n + calculator.join();
25+
}
26+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.baeldung.concurrent.future;
2+
3+
import static org.junit.Assert.assertEquals;
4+
5+
import java.util.concurrent.ForkJoinPool;
6+
7+
import org.junit.Test;
8+
9+
public class FactorialSquareCalculatorUnitTest {
10+
11+
@Test
12+
public void whenCalculatesFactorialSquare_thenReturnCorrectValue() {
13+
ForkJoinPool forkJoinPool = new ForkJoinPool();
14+
15+
FactorialSquareCalculator calculator = new FactorialSquareCalculator(10);
16+
17+
forkJoinPool.execute(calculator);
18+
19+
assertEquals("The sum of the squares from 1 to 10 is 385", 385, calculator.join().intValue());
20+
}
21+
22+
}

0 commit comments

Comments
 (0)