BAEL-612: Example usage of ForkJoinTask

This commit is contained in:
Felipe Reis 2017-01-26 17:22:45 -02:00
parent f36d7f1ac2
commit c0756273ca
2 changed files with 48 additions and 0 deletions

View File

@ -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();
}
}

View File

@ -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());
}
}