1111import java .util .Random ;
1212import java .util .concurrent .CompletableFuture ;
1313import java .util .concurrent .CompletionException ;
14+ import java .util .concurrent .Executor ;
1415import java .util .concurrent .ExecutorService ;
1516import java .util .concurrent .Executors ;
17+ import java .util .concurrent .ScheduledThreadPoolExecutor ;
1618import java .util .concurrent .ThreadFactory ;
1719import java .util .concurrent .TimeUnit ;
1820import java .util .stream .Collectors ;
@@ -30,9 +32,28 @@ public Thread newThread(Runnable runnable) {
3032
3133 static Random random = new Random ();
3234
35+ static ScheduledThreadPoolExecutor delayer = new ScheduledThreadPoolExecutor (1 , new ThreadFactory () {
36+
37+ @ Override
38+ public Thread newThread (Runnable r ) {
39+ Thread t = new Thread (r );
40+ t .setDaemon (true );
41+ t .setName ("CompletableFutureDelayScheduler" );
42+ return t ;
43+ }
44+ });
45+
46+ static Executor delayedExecutor = new Executor () {
47+
48+ @ Override
49+ public void execute (Runnable r ) {
50+ delayer .schedule (r , 1000 , TimeUnit .MILLISECONDS );
51+ }
52+ };
53+
3354 public static void main (String [] args ) {
3455 try {
35- // allOfAsyncExample ();
56+ completedFutureExample ();
3657 } finally {
3758 executor .shutdown ();
3859 }
@@ -46,7 +67,7 @@ static void completedFutureExample() {
4667
4768 static void completeExceptionallyExample () {
4869 CompletableFuture <String > cf = CompletableFuture .completedFuture ("message" ).thenApplyAsync (String ::toUpperCase ,
49- CompletableFuture . delayedExecutor ( 1 , TimeUnit . SECONDS ) );
70+ delayedExecutor );
5071 CompletableFuture <String > exceptionHandler = cf .handle ((s , th ) -> { return (th != null ) ? "message upon cancel" : "" ; });
5172 cf .completeExceptionally (new RuntimeException ("completed exceptionally" ));
5273 assertTrue ("Was not completed exceptionally" , cf .isCompletedExceptionally ());
@@ -117,7 +138,7 @@ static void thenAcceptAsyncExample() {
117138
118139 static void cancelExample () {
119140 CompletableFuture <String > cf = CompletableFuture .completedFuture ("message" ).thenApplyAsync (String ::toUpperCase ,
120- CompletableFuture . delayedExecutor ( 1 , TimeUnit . SECONDS ) );
141+ delayedExecutor );
121142 CompletableFuture <String > cf2 = cf .exceptionally (throwable -> "canceled message" );
122143 assertTrue ("Was not canceled" , cf .cancel (true ));
123144 assertTrue ("Was not completed exceptionally" , cf .isCompletedExceptionally ());
0 commit comments