From 38bd9bbac12fb7d51794f6918e5b81297a36e968 Mon Sep 17 00:00:00 2001 From: manouti Date: Fri, 30 Mar 2018 22:40:53 +0300 Subject: [PATCH] Update examples to work on Java 8 --- .../CompletableFutureExamples.java | 27 ++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/example/completablefuture/CompletableFutureExamples.java b/src/main/java/com/example/completablefuture/CompletableFutureExamples.java index c02e22e..4d4a6ab 100644 --- a/src/main/java/com/example/completablefuture/CompletableFutureExamples.java +++ b/src/main/java/com/example/completablefuture/CompletableFutureExamples.java @@ -11,8 +11,10 @@ import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; +import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @@ -30,9 +32,28 @@ public Thread newThread(Runnable runnable) { static Random random = new Random(); + static ScheduledThreadPoolExecutor delayer = new ScheduledThreadPoolExecutor(1, new ThreadFactory() { + + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r); + t.setDaemon(true); + t.setName("CompletableFutureDelayScheduler"); + return t; + } + }); + + static Executor delayedExecutor = new Executor() { + + @Override + public void execute(Runnable r) { + delayer.schedule(r, 1000, TimeUnit.MILLISECONDS); + } + }; + public static void main(String[] args) { try { -// allOfAsyncExample(); + completedFutureExample(); } finally { executor.shutdown(); } @@ -46,7 +67,7 @@ static void completedFutureExample() { static void completeExceptionallyExample() { CompletableFuture cf = CompletableFuture.completedFuture("message").thenApplyAsync(String::toUpperCase, - CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS)); + delayedExecutor); CompletableFuture exceptionHandler = cf.handle((s, th) -> { return (th != null) ? "message upon cancel" : ""; }); cf.completeExceptionally(new RuntimeException("completed exceptionally")); assertTrue("Was not completed exceptionally", cf.isCompletedExceptionally()); @@ -117,7 +138,7 @@ static void thenAcceptAsyncExample() { static void cancelExample() { CompletableFuture cf = CompletableFuture.completedFuture("message").thenApplyAsync(String::toUpperCase, - CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS)); + delayedExecutor); CompletableFuture cf2 = cf.exceptionally(throwable -> "canceled message"); assertTrue("Was not canceled", cf.cancel(true)); assertTrue("Was not completed exceptionally", cf.isCompletedExceptionally());