SHARE
TWEET

Untitled

a guest Oct 21st, 2019 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package sd.lab.concurrency.exercise;
  2.  
  3. import java.math.BigInteger;
  4. import java.util.concurrent.CompletableFuture;
  5. import java.util.concurrent.ExecutorService;
  6.  
  7. public interface AsyncCalculator {
  8.  
  9.     default CompletableFuture<BigInteger> factorial(long x) {
  10.         return factorial(BigInteger.valueOf(x));
  11.     }
  12.  
  13.     CompletableFuture<BigInteger> factorial(BigInteger valueOf);
  14.  
  15.     static AsyncCalculator newInstance(ExecutorService executorService) {
  16.         return new AsyncCalculator() {
  17.             @Override
  18.             public CompletableFuture<BigInteger> factorial(BigInteger valueOf) {
  19.                 final CompletableFuture<BigInteger> resultPromise = new CompletableFuture<>();
  20.                 executorService.execute(() -> factorialImpl(BigInteger.ZERO, valueOf, BigInteger.ONE, resultPromise));
  21.                 return resultPromise;
  22.             }
  23.  
  24.             private void factorialImpl(BigInteger current, BigInteger upto, BigInteger currentRes, CompletableFuture<BigInteger> future){
  25.                 if(upto.compareTo(BigInteger.ZERO) < 0) {
  26.                     future.completeExceptionally(new IllegalArgumentException("Cannot compute factorial for negative numbers"));
  27.                 } else if (upto.compareTo(BigInteger.ZERO) == 0) {
  28.                     future.complete(BigInteger.ONE);
  29.                 } else if (current.compareTo(upto) == 0) {
  30.                     future.complete(currentRes);
  31.                 } else if (current.compareTo(upto) < 0) {
  32.                     BigInteger current_ = current.add(BigInteger.ONE);
  33.                     BigInteger currentRes_ = currentRes.multiply(current_);
  34.                     executorService.execute(() -> factorialImpl(current_, upto, currentRes_, future));
  35.                 }
  36.             }
  37.         };
  38.     }
  39. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top