BAEL-612: Example usage of ForkJoinTask
This commit is contained in:
parent
f36d7f1ac2
commit
c0756273ca
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.concurrent.future;
|
||||
|
||||
import java.util.concurrent.RecursiveTask;
|
||||
|
||||
public class FactorialSquareCalculator extends RecursiveTask<Integer> {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
final private Integer n;
|
||||
|
||||
public FactorialSquareCalculator(Integer n) {
|
||||
this.n = n;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Integer compute() {
|
||||
if (n <= 1) {
|
||||
return n;
|
||||
}
|
||||
|
||||
FactorialSquareCalculator calculator = new FactorialSquareCalculator(n - 1);
|
||||
|
||||
calculator.fork();
|
||||
|
||||
return n * n + calculator.join();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.concurrent.future;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FactorialSquareCalculatorUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCalculatesFactorialSquare_thenReturnCorrectValue() {
|
||||
ForkJoinPool forkJoinPool = new ForkJoinPool();
|
||||
|
||||
FactorialSquareCalculator calculator = new FactorialSquareCalculator(10);
|
||||
|
||||
forkJoinPool.execute(calculator);
|
||||
|
||||
assertEquals("The sum of the squares from 1 to 10 is 385", 385, calculator.join().intValue());
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue