package futures; import java.util.concurrent.*; import java.util.function.Supplier; /** * Goal: write parallel Fibonacci without using any blocking calls (except at the very end). */ public class FibExec3 { final static ExecutorService exec = new MyExecutor(8); // final static ExecutorService exec = new ForkJoinPool(8); public static CompletableFuture supplyAsyncFut(Supplier> supplier, Executor executor) { final CompletableFuture result = new CompletableFuture<>(); CompletableFuture.runAsync(() -> { supplier.get().thenAccept((v) -> { result.complete(v); }); }, executor); return result; } static CompletableFuture fcall(int n) { if (n < 2) return CompletableFuture.completedFuture(n); CompletableFuture f1 = supplyAsyncFut(() -> fcall(n - 1), exec); CompletableFuture f2 = fcall(n - 2); return f1.thenCombine(f2, (a, b) -> a + b); } public static void main(String[] args) throws Exception { for (int n = 0; n <= 47; n++) { long t1 = System.currentTimeMillis(); long f = fcall(n).join(); long t2 = System.currentTimeMillis(); double tm = 1e-3 * (t2 - t1); System.out.printf("fib(%d)=%d, time=%f%n", n, f, tm); } exec.shutdown(); } }