Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package sd.lab.concurrency.exercise;
- import java.math.BigInteger;
- import java.util.concurrent.CompletableFuture;
- import java.util.concurrent.ExecutorService;
- public class AsyncCalculatorImpl implements AsyncCalculator {
- private final ExecutorService executor;
- private volatile BigInteger value = BigInteger.ONE;
- public AsyncCalculatorImpl(ExecutorService executor) {
- this.executor = executor;
- }
- @Override
- public CompletableFuture<BigInteger> factorial(BigInteger valueOf) {
- if (valueOf.signum() == -1) throw new IllegalArgumentException("Cannot compute factorial for negative numbers");
- final CompletableFuture<BigInteger> resultPromise = new CompletableFuture<>();
- executor.execute(() -> factorialImpl(valueOf, resultPromise));
- return resultPromise;
- }
- private void factorialImpl(BigInteger valueOf, CompletableFuture<BigInteger> resultPromise) {
- if (valueOf.equals(BigInteger.ZERO)) {
- resultPromise.complete(value);
- } else {
- value.multiply(valueOf);
- System.out.println(value.toString());
- executor.execute(() -> factorialImpl(valueOf.subtract(BigInteger.ONE), resultPromise));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement