Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  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 class AsyncCalculatorImpl implements AsyncCalculator {
  8.  
  9. private final ExecutorService executor;
  10. private volatile BigInteger value = BigInteger.ONE;
  11.  
  12. public AsyncCalculatorImpl(ExecutorService executor) {
  13. this.executor = executor;
  14. }
  15.  
  16. @Override
  17. public CompletableFuture<BigInteger> factorial(BigInteger valueOf) {
  18. if (valueOf.signum() == -1) throw new IllegalArgumentException("Cannot compute factorial for negative numbers");
  19. final CompletableFuture<BigInteger> resultPromise = new CompletableFuture<>();
  20. executor.execute(() -> factorialImpl(valueOf, resultPromise));
  21. return resultPromise;
  22. }
  23.  
  24. private void factorialImpl(BigInteger valueOf, CompletableFuture<BigInteger> resultPromise) {
  25. if (valueOf.equals(BigInteger.ZERO)) {
  26. resultPromise.complete(value);
  27. } else {
  28. value.multiply(valueOf);
  29. System.out.println(value.toString());
  30. executor.execute(() -> factorialImpl(valueOf.subtract(BigInteger.ONE), resultPromise));
  31. }
  32. }
  33.  
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement