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 interface AsyncCalculator {
- default CompletableFuture<BigInteger> factorial(long x) {
- return factorial(BigInteger.valueOf(x));
- }
- CompletableFuture<BigInteger> factorial(BigInteger valueOf);
- static AsyncCalculator newInstance(ExecutorService executorService) {
- return new AsyncCalculator() {
- @Override
- public CompletableFuture<BigInteger> factorial(BigInteger valueOf) {
- final CompletableFuture<BigInteger> resultPromise = new CompletableFuture<>();
- executorService.execute(() -> factorialImpl(BigInteger.ZERO, valueOf, BigInteger.ONE, resultPromise));
- return resultPromise;
- }
- private void factorialImpl(BigInteger current, BigInteger upto, BigInteger currentRes, CompletableFuture<BigInteger> future){
- if(upto.compareTo(BigInteger.ZERO) < 0) {
- future.completeExceptionally(new IllegalArgumentException("Cannot compute factorial for negative numbers"));
- } else if (upto.compareTo(BigInteger.ZERO) == 0) {
- future.complete(BigInteger.ONE);
- } else if (current.compareTo(upto) == 0) {
- future.complete(currentRes);
- } else if (current.compareTo(upto) < 0) {
- BigInteger current_ = current.add(BigInteger.ONE);
- BigInteger currentRes_ = currentRes.multiply(current_);
- executorService.execute(() -> factorialImpl(current_, upto, currentRes_, future));
- }
- }
- };
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement