--- jsr166/src/test/tck/CompletableFutureTest.java 2015/09/03 11:45:34 1.103 +++ jsr166/src/test/tck/CompletableFutureTest.java 2016/04/11 06:31:42 1.146 @@ -7,10 +7,20 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; +import static java.util.concurrent.CompletableFuture.completedFuture; +import static java.util.concurrent.CompletableFuture.failedFuture; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import java.util.stream.Collectors; +import java.util.stream.Stream; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Objects; +import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.CompletableFuture; @@ -28,8 +38,10 @@ import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; +import java.util.function.Predicate; import java.util.function.Supplier; +import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestSuite; @@ -77,142 +89,94 @@ public class CompletableFutureTest exten assertTrue(f.toString().contains("[Completed normally]")); } - void checkCompletedWithWrappedCFException(CompletableFuture f) { - long startTime = System.nanoTime(); - long timeoutMillis = LONG_DELAY_MS; - try { - f.get(timeoutMillis, MILLISECONDS); - shouldThrow(); - } catch (ExecutionException success) { - assertTrue(success.getCause() instanceof CFException); - } catch (Throwable fail) { threadUnexpectedException(fail); } - assertTrue(millisElapsedSince(startTime) < timeoutMillis/2); - - try { - f.join(); - shouldThrow(); - } catch (CompletionException success) { - assertTrue(success.getCause() instanceof CFException); - } - try { - f.getNow(null); - shouldThrow(); - } catch (CompletionException success) { - assertTrue(success.getCause() instanceof CFException); + /** + * Returns the "raw" internal exceptional completion of f, + * without any additional wrapping with CompletionException. + */ + Throwable exceptionalCompletion(CompletableFuture f) { + // handle (and whenComplete) can distinguish between "direct" + // and "wrapped" exceptional completion + return f.handle((U u, Throwable t) -> t).join(); + } + + void checkCompletedExceptionally(CompletableFuture f, + boolean wrapped, + Consumer checker) { + Throwable cause = exceptionalCompletion(f); + if (wrapped) { + assertTrue(cause instanceof CompletionException); + cause = cause.getCause(); } - try { - f.get(); - shouldThrow(); - } catch (ExecutionException success) { - assertTrue(success.getCause() instanceof CFException); - } catch (Throwable fail) { threadUnexpectedException(fail); } - assertTrue(f.isDone()); - assertFalse(f.isCancelled()); - assertTrue(f.toString().contains("[Completed exceptionally]")); - } + checker.accept(cause); - void checkCompletedExceptionallyWithRootCause(CompletableFuture f, - Throwable ex) { long startTime = System.nanoTime(); - long timeoutMillis = LONG_DELAY_MS; try { - f.get(timeoutMillis, MILLISECONDS); + f.get(LONG_DELAY_MS, MILLISECONDS); shouldThrow(); } catch (ExecutionException success) { - assertSame(ex, success.getCause()); + assertSame(cause, success.getCause()); } catch (Throwable fail) { threadUnexpectedException(fail); } - assertTrue(millisElapsedSince(startTime) < timeoutMillis/2); + assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2); try { f.join(); shouldThrow(); } catch (CompletionException success) { - assertSame(ex, success.getCause()); - } + assertSame(cause, success.getCause()); + } catch (Throwable fail) { threadUnexpectedException(fail); } + try { f.getNow(null); shouldThrow(); } catch (CompletionException success) { - assertSame(ex, success.getCause()); - } + assertSame(cause, success.getCause()); + } catch (Throwable fail) { threadUnexpectedException(fail); } + try { f.get(); shouldThrow(); } catch (ExecutionException success) { - assertSame(ex, success.getCause()); + assertSame(cause, success.getCause()); } catch (Throwable fail) { threadUnexpectedException(fail); } - assertTrue(f.isDone()); assertFalse(f.isCancelled()); + assertTrue(f.isDone()); + assertTrue(f.isCompletedExceptionally()); assertTrue(f.toString().contains("[Completed exceptionally]")); } - void checkCompletedExceptionallyWithTimeout(CompletableFuture f) { - long startTime = System.nanoTime(); - long timeoutMillis = LONG_DELAY_MS; - try { - f.get(timeoutMillis, MILLISECONDS); - shouldThrow(); - } catch (ExecutionException ex) { - assertTrue(ex.getCause() instanceof TimeoutException); - } catch (Throwable fail) { threadUnexpectedException(fail); } - assertTrue(millisElapsedSince(startTime) < timeoutMillis/2); - - try { - f.join(); - shouldThrow(); - } catch (Throwable ex) { - assertTrue(ex.getCause() instanceof TimeoutException); - } - - try { - f.getNow(null); - shouldThrow(); - } catch (Throwable ex) { - assertTrue(ex.getCause() instanceof TimeoutException); - } + void checkCompletedWithWrappedCFException(CompletableFuture f) { + checkCompletedExceptionally(f, true, + (t) -> assertTrue(t instanceof CFException)); + } - try { - f.get(); - shouldThrow(); - } catch (ExecutionException ex) { - assertTrue(ex.getCause() instanceof TimeoutException); - } catch (Throwable fail) { threadUnexpectedException(fail); } + void checkCompletedWithWrappedCancellationException(CompletableFuture f) { + checkCompletedExceptionally(f, true, + (t) -> assertTrue(t instanceof CancellationException)); + } - assertTrue(f.isDone()); - assertFalse(f.isCancelled()); - assertTrue(f.toString().contains("[Completed exceptionally]")); + void checkCompletedWithTimeoutException(CompletableFuture f) { + checkCompletedExceptionally(f, false, + (t) -> assertTrue(t instanceof TimeoutException)); } - void checkCompletedWithWrappedException(CompletableFuture f, - Throwable ex) { - checkCompletedExceptionallyWithRootCause(f, ex); - try { - CompletableFuture spy = f.handle - ((U u, Throwable t) -> t); - assertTrue(spy.join() instanceof CompletionException); - assertSame(ex, spy.join().getCause()); - } catch (Throwable fail) { threadUnexpectedException(fail); } + void checkCompletedWithWrappedException(CompletableFuture f, + Throwable ex) { + checkCompletedExceptionally(f, true, (t) -> assertSame(t, ex)); } - void checkCompletedExceptionally(CompletableFuture f, Throwable ex) { - checkCompletedExceptionallyWithRootCause(f, ex); - try { - CompletableFuture spy = f.handle - ((U u, Throwable t) -> t); - assertSame(ex, spy.join()); - } catch (Throwable fail) { threadUnexpectedException(fail); } + void checkCompletedExceptionally(CompletableFuture f, Throwable ex) { + checkCompletedExceptionally(f, false, (t) -> assertSame(t, ex)); } void checkCancelled(CompletableFuture f) { long startTime = System.nanoTime(); - long timeoutMillis = LONG_DELAY_MS; try { - f.get(timeoutMillis, MILLISECONDS); + f.get(LONG_DELAY_MS, MILLISECONDS); shouldThrow(); } catch (CancellationException success) { } catch (Throwable fail) { threadUnexpectedException(fail); } - assertTrue(millisElapsedSince(startTime) < timeoutMillis/2); + assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2); try { f.join(); @@ -227,44 +191,12 @@ public class CompletableFutureTest exten shouldThrow(); } catch (CancellationException success) { } catch (Throwable fail) { threadUnexpectedException(fail); } - assertTrue(f.isDone()); - assertTrue(f.isCompletedExceptionally()); - assertTrue(f.isCancelled()); - assertTrue(f.toString().contains("[Completed exceptionally]")); - } - void checkCompletedWithWrappedCancellationException(CompletableFuture f) { - long startTime = System.nanoTime(); - long timeoutMillis = LONG_DELAY_MS; - try { - f.get(timeoutMillis, MILLISECONDS); - shouldThrow(); - } catch (ExecutionException success) { - assertTrue(success.getCause() instanceof CancellationException); - } catch (Throwable fail) { threadUnexpectedException(fail); } - assertTrue(millisElapsedSince(startTime) < timeoutMillis/2); + assertTrue(exceptionalCompletion(f) instanceof CancellationException); - try { - f.join(); - shouldThrow(); - } catch (CompletionException success) { - assertTrue(success.getCause() instanceof CancellationException); - } - try { - f.getNow(null); - shouldThrow(); - } catch (CompletionException success) { - assertTrue(success.getCause() instanceof CancellationException); - } - try { - f.get(); - shouldThrow(); - } catch (ExecutionException success) { - assertTrue(success.getCause() instanceof CancellationException); - } catch (Throwable fail) { threadUnexpectedException(fail); } assertTrue(f.isDone()); - assertFalse(f.isCancelled()); assertTrue(f.isCompletedExceptionally()); + assertTrue(f.isCancelled()); assertTrue(f.toString().contains("[Completed exceptionally]")); } @@ -908,9 +840,9 @@ public class CompletableFutureTest exten if (!createIncomplete) assertTrue(f.complete(v1)); final CompletableFuture g = f.exceptionally ((Throwable t) -> { - // Should not be called a.getAndIncrement(); - throw new AssertionError(); + threadFail("should not be called"); + return null; // unreached }); if (createIncomplete) assertTrue(f.complete(v1)); @@ -944,6 +876,10 @@ public class CompletableFutureTest exten assertEquals(1, a.get()); }} + /** + * If an "exceptionally action" throws an exception, it completes + * exceptionally with that exception + */ public void testExceptionally_exceptionalCompletionActionFailed() { for (boolean createIncomplete : new boolean[] { true, false }) { @@ -962,6 +898,7 @@ public class CompletableFutureTest exten if (createIncomplete) f.completeExceptionally(ex1); checkCompletedWithWrappedException(g, ex2); + checkCompletedExceptionally(f, ex1); assertEquals(1, a.get()); }} @@ -969,7 +906,7 @@ public class CompletableFutureTest exten * whenComplete action executes on normal completion, propagating * source result. */ - public void testWhenComplete_normalCompletion1() { + public void testWhenComplete_normalCompletion() { for (ExecutionMode m : ExecutionMode.values()) for (boolean createIncomplete : new boolean[] { true, false }) for (Integer v1 : new Integer[] { 1, null }) @@ -979,9 +916,9 @@ public class CompletableFutureTest exten if (!createIncomplete) assertTrue(f.complete(v1)); final CompletableFuture g = m.whenComplete (f, - (Integer x, Throwable t) -> { + (Integer result, Throwable t) -> { m.checkExecutionMode(); - threadAssertSame(x, v1); + threadAssertSame(result, v1); threadAssertNull(t); a.getAndIncrement(); }); @@ -1006,9 +943,9 @@ public class CompletableFutureTest exten if (!createIncomplete) f.completeExceptionally(ex); final CompletableFuture g = m.whenComplete (f, - (Integer x, Throwable t) -> { + (Integer result, Throwable t) -> { m.checkExecutionMode(); - threadAssertNull(x); + threadAssertNull(result); threadAssertSame(t, ex); a.getAndIncrement(); }); @@ -1033,9 +970,9 @@ public class CompletableFutureTest exten if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning)); final CompletableFuture g = m.whenComplete (f, - (Integer x, Throwable t) -> { + (Integer result, Throwable t) -> { m.checkExecutionMode(); - threadAssertNull(x); + threadAssertNull(result); threadAssertTrue(t instanceof CancellationException); a.getAndIncrement(); }); @@ -1050,7 +987,7 @@ public class CompletableFutureTest exten * If a whenComplete action throws an exception when triggered by * a normal completion, it completes exceptionally */ - public void testWhenComplete_actionFailed() { + public void testWhenComplete_sourceCompletedNormallyActionFailed() { for (boolean createIncomplete : new boolean[] { true, false }) for (ExecutionMode m : ExecutionMode.values()) for (Integer v1 : new Integer[] { 1, null }) @@ -1061,9 +998,9 @@ public class CompletableFutureTest exten if (!createIncomplete) assertTrue(f.complete(v1)); final CompletableFuture g = m.whenComplete (f, - (Integer x, Throwable t) -> { + (Integer result, Throwable t) -> { m.checkExecutionMode(); - threadAssertSame(x, v1); + threadAssertSame(result, v1); threadAssertNull(t); a.getAndIncrement(); throw ex; @@ -1078,9 +1015,9 @@ public class CompletableFutureTest exten /** * If a whenComplete action throws an exception when triggered by * a source completion that also throws an exception, the source - * exception takes precedence. + * exception takes precedence (unlike handle) */ - public void testWhenComplete_actionFailedSourceFailed() { + public void testWhenComplete_sourceFailedActionFailed() { for (boolean createIncomplete : new boolean[] { true, false }) for (ExecutionMode m : ExecutionMode.values()) { @@ -1092,10 +1029,10 @@ public class CompletableFutureTest exten if (!createIncomplete) f.completeExceptionally(ex1); final CompletableFuture g = m.whenComplete (f, - (Integer x, Throwable t) -> { + (Integer result, Throwable t) -> { m.checkExecutionMode(); threadAssertSame(t, ex1); - threadAssertNull(x); + threadAssertNull(result); a.getAndIncrement(); throw ex2; }); @@ -1103,6 +1040,10 @@ public class CompletableFutureTest exten checkCompletedWithWrappedException(g, ex1); checkCompletedExceptionally(f, ex1); + if (testImplementationDetails) { + assertEquals(1, ex1.getSuppressed().length); + assertSame(ex2, ex1.getSuppressed()[0]); + } assertEquals(1, a.get()); }} @@ -1120,9 +1061,9 @@ public class CompletableFutureTest exten if (!createIncomplete) assertTrue(f.complete(v1)); final CompletableFuture g = m.handle (f, - (Integer x, Throwable t) -> { + (Integer result, Throwable t) -> { m.checkExecutionMode(); - threadAssertSame(x, v1); + threadAssertSame(result, v1); threadAssertNull(t); a.getAndIncrement(); return inc(v1); @@ -1149,9 +1090,9 @@ public class CompletableFutureTest exten if (!createIncomplete) f.completeExceptionally(ex); final CompletableFuture g = m.handle (f, - (Integer x, Throwable t) -> { + (Integer result, Throwable t) -> { m.checkExecutionMode(); - threadAssertNull(x); + threadAssertNull(result); threadAssertSame(t, ex); a.getAndIncrement(); return v1; @@ -1178,9 +1119,9 @@ public class CompletableFutureTest exten if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning)); final CompletableFuture g = m.handle (f, - (Integer x, Throwable t) -> { + (Integer result, Throwable t) -> { m.checkExecutionMode(); - threadAssertNull(x); + threadAssertNull(result); threadAssertTrue(t instanceof CancellationException); a.getAndIncrement(); return v1; @@ -1193,55 +1134,62 @@ public class CompletableFutureTest exten }} /** - * handle result completes exceptionally if action does + * If a "handle action" throws an exception when triggered by + * a normal completion, it completes exceptionally */ - public void testHandle_sourceFailedActionFailed() { + public void testHandle_sourceCompletedNormallyActionFailed() { for (ExecutionMode m : ExecutionMode.values()) for (boolean createIncomplete : new boolean[] { true, false }) + for (Integer v1 : new Integer[] { 1, null }) { final CompletableFuture f = new CompletableFuture<>(); final AtomicInteger a = new AtomicInteger(0); - final CFException ex1 = new CFException(); - final CFException ex2 = new CFException(); - if (!createIncomplete) f.completeExceptionally(ex1); + final CFException ex = new CFException(); + if (!createIncomplete) assertTrue(f.complete(v1)); final CompletableFuture g = m.handle (f, - (Integer x, Throwable t) -> { + (Integer result, Throwable t) -> { m.checkExecutionMode(); - threadAssertNull(x); - threadAssertSame(ex1, t); + threadAssertSame(result, v1); + threadAssertNull(t); a.getAndIncrement(); - throw ex2; + throw ex; }); - if (createIncomplete) f.completeExceptionally(ex1); + if (createIncomplete) assertTrue(f.complete(v1)); - checkCompletedWithWrappedException(g, ex2); - checkCompletedExceptionally(f, ex1); + checkCompletedWithWrappedException(g, ex); + checkCompletedNormally(f, v1); assertEquals(1, a.get()); }} - public void testHandle_sourceCompletedNormallyActionFailed() { - for (ExecutionMode m : ExecutionMode.values()) + /** + * If a "handle action" throws an exception when triggered by + * a source completion that also throws an exception, the action + * exception takes precedence (unlike whenComplete) + */ + public void testHandle_sourceFailedActionFailed() { for (boolean createIncomplete : new boolean[] { true, false }) - for (Integer v1 : new Integer[] { 1, null }) + for (ExecutionMode m : ExecutionMode.values()) { - final CompletableFuture f = new CompletableFuture<>(); final AtomicInteger a = new AtomicInteger(0); - final CFException ex = new CFException(); - if (!createIncomplete) assertTrue(f.complete(v1)); + final CFException ex1 = new CFException(); + final CFException ex2 = new CFException(); + final CompletableFuture f = new CompletableFuture<>(); + + if (!createIncomplete) f.completeExceptionally(ex1); final CompletableFuture g = m.handle (f, - (Integer x, Throwable t) -> { + (Integer result, Throwable t) -> { m.checkExecutionMode(); - threadAssertSame(x, v1); - threadAssertNull(t); + threadAssertNull(result); + threadAssertSame(ex1, t); a.getAndIncrement(); - throw ex; + throw ex2; }); - if (createIncomplete) assertTrue(f.complete(v1)); + if (createIncomplete) f.completeExceptionally(ex1); - checkCompletedWithWrappedException(g, ex); - checkCompletedNormally(f, v1); + checkCompletedWithWrappedException(g, ex2); + checkCompletedExceptionally(f, ex1); assertEquals(1, a.get()); }} @@ -3142,7 +3090,7 @@ public class CompletableFutureTest exten for (int i = 0; i < k; i++) { checkIncomplete(f); checkIncomplete(CompletableFuture.allOf(fs)); - if (i != k/2) { + if (i != k / 2) { fs[i].complete(i); checkCompletedNormally(fs[i], i); } else { @@ -3333,6 +3281,7 @@ public class CompletableFutureTest exten () -> f.exceptionally(null), () -> f.handle(null), + () -> CompletableFuture.allOf((CompletableFuture)null), () -> CompletableFuture.allOf((CompletableFuture[])null), () -> CompletableFuture.allOf(f, null), @@ -3344,6 +3293,16 @@ public class CompletableFutureTest exten () -> CompletableFuture.anyOf(null, f), () -> f.obtrudeException(null), + + () -> CompletableFuture.delayedExecutor(1L, SECONDS, null), + () -> CompletableFuture.delayedExecutor(1L, null, exec), + () -> CompletableFuture.delayedExecutor(1L, null), + + () -> f.orTimeout(1L, null), + () -> f.completeOnTimeout(42, 1L, null), + + () -> CompletableFuture.failedFuture(null), + () -> CompletableFuture.failedStage(null), }; assertThrows(NullPointerException.class, throwingActions); @@ -3359,22 +3318,30 @@ public class CompletableFutureTest exten } // jdk9 - + /** * newIncompleteFuture returns an incomplete CompletableFuture */ public void testNewIncompleteFuture() { + for (Integer v1 : new Integer[] { 1, null }) + { CompletableFuture f = new CompletableFuture<>(); CompletableFuture g = f.newIncompleteFuture(); checkIncomplete(f); checkIncomplete(g); - } + f.complete(v1); + checkCompletedNormally(f, v1); + checkIncomplete(g); + g.complete(v1); + checkCompletedNormally(g, v1); + assertSame(g.getClass(), CompletableFuture.class); + }} /** * completedStage returns a completed CompletionStage */ public void testCompletedStage() { - AtomicInteger x = new AtomicInteger(); + AtomicInteger x = new AtomicInteger(0); AtomicReference r = new AtomicReference(); CompletionStage f = CompletableFuture.completedStage(1); f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);}); @@ -3384,14 +3351,16 @@ public class CompletableFutureTest exten /** * defaultExecutor by default returns the commonPool if - * it supports at least one thread. + * it supports more than one thread. */ public void testDefaultExecutor() { CompletableFuture f = new CompletableFuture<>(); Executor e = f.defaultExecutor(); - Executor c = ForkJoinPool.commonPool(); - if (ForkJoinPool.getCommonPoolParallelism() > 0) + Executor c = ForkJoinPool.commonPool(); + if (ForkJoinPool.getCommonPoolParallelism() > 1) assertSame(e, c); + else + assertNotSame(e, c); } /** @@ -3401,17 +3370,17 @@ public class CompletableFutureTest exten public void testFailedFuture() { CFException ex = new CFException(); CompletableFuture f = CompletableFuture.failedFuture(ex); - checkCompletedExceptionallyWithRootCause(f, ex); + checkCompletedExceptionally(f, ex); } /** * failedFuture(null) throws NPE */ - public void testFailedFuture2() { + public void testFailedFuture_null() { try { CompletableFuture f = CompletableFuture.failedFuture(null); - } catch(NullPointerException success) { - } + shouldThrow(); + } catch (NullPointerException success) {} } /** @@ -3440,7 +3409,7 @@ public class CompletableFutureTest exten CFException ex = new CFException(); f.completeExceptionally(ex); checkCompletedExceptionally(f, ex); - checkCompletedWithWrappedCFException(g); + checkCompletedWithWrappedException(g, ex); } /** @@ -3450,7 +3419,7 @@ public class CompletableFutureTest exten public void testMinimalCompletionStage() { CompletableFuture f = new CompletableFuture<>(); CompletionStage g = f.minimalCompletionStage(); - AtomicInteger x = new AtomicInteger(); + AtomicInteger x = new AtomicInteger(0); AtomicReference r = new AtomicReference(); checkIncomplete(f); g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);}); @@ -3467,7 +3436,7 @@ public class CompletableFutureTest exten public void testMinimalCompletionStage2() { CompletableFuture f = new CompletableFuture<>(); CompletionStage g = f.minimalCompletionStage(); - AtomicInteger x = new AtomicInteger(); + AtomicInteger x = new AtomicInteger(0); AtomicReference r = new AtomicReference(); g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);}); checkIncomplete(f); @@ -3479,28 +3448,30 @@ public class CompletableFutureTest exten } /** - * failedStage returns a Completionstage completed + * failedStage returns a CompletionStage completed * exceptionally with the given Exception */ public void testFailedStage() { CFException ex = new CFException(); CompletionStage f = CompletableFuture.failedStage(ex); - AtomicInteger x = new AtomicInteger(); + AtomicInteger x = new AtomicInteger(0); AtomicReference r = new AtomicReference(); f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);}); assertEquals(x.get(), 0); - assertEquals(r.get().getCause(), ex); + assertEquals(r.get(), ex); } /** * completeAsync completes with value of given supplier */ public void testCompleteAsync() { + for (Integer v1 : new Integer[] { 1, null }) + { CompletableFuture f = new CompletableFuture<>(); - f.completeAsync(() -> 1); + f.completeAsync(() -> v1); f.join(); - checkCompletedNormally(f, 1); - } + checkCompletedNormally(f, v1); + }} /** * completeAsync completes exceptionally if given supplier throws @@ -3512,20 +3483,23 @@ public class CompletableFutureTest exten try { f.join(); shouldThrow(); - } catch(Exception success) { - } - checkCompletedWithWrappedCFException(f); + } catch (CompletionException success) {} + checkCompletedWithWrappedException(f, ex); } /** * completeAsync with given executor completes with value of given supplier */ public void testCompleteAsync3() { + for (Integer v1 : new Integer[] { 1, null }) + { CompletableFuture f = new CompletableFuture<>(); - f.completeAsync(() -> 1, new ThreadExecutor()); - f.join(); - checkCompletedNormally(f, 1); - } + ThreadExecutor executor = new ThreadExecutor(); + f.completeAsync(() -> v1, executor); + assertSame(v1, f.join()); + checkCompletedNormally(f, v1); + assertEquals(1, executor.count.get()); + }} /** * completeAsync with given executor completes exceptionally if @@ -3534,88 +3508,125 @@ public class CompletableFutureTest exten public void testCompleteAsync4() { CompletableFuture f = new CompletableFuture<>(); CFException ex = new CFException(); - f.completeAsync(() -> {if (true) throw ex; return 1;}, new ThreadExecutor()); + ThreadExecutor executor = new ThreadExecutor(); + f.completeAsync(() -> {if (true) throw ex; return 1;}, executor); try { f.join(); shouldThrow(); - } catch(Exception success) { - } - checkCompletedWithWrappedCFException(f); + } catch (CompletionException success) {} + checkCompletedWithWrappedException(f, ex); + assertEquals(1, executor.count.get()); } /** - * orTimeout completes with TimeoutException if not complete + * orTimeout completes with TimeoutException if not complete */ - public void testOrTimeout() { + public void testOrTimeout_timesOut() { + long timeoutMillis = timeoutMillis(); CompletableFuture f = new CompletableFuture<>(); - f.orTimeout(SHORT_DELAY_MS, TimeUnit.MILLISECONDS); - checkCompletedExceptionallyWithTimeout(f); + long startTime = System.nanoTime(); + assertSame(f, f.orTimeout(timeoutMillis, MILLISECONDS)); + checkCompletedWithTimeoutException(f); + assertTrue(millisElapsedSince(startTime) >= timeoutMillis); } /** - * orTimeout completes normally if completed before timeout + * orTimeout completes normally if completed before timeout */ - public void testOrTimeout2() { + public void testOrTimeout_completed() { + for (Integer v1 : new Integer[] { 1, null }) + { CompletableFuture f = new CompletableFuture<>(); - f.complete(1); - f.orTimeout(SHORT_DELAY_MS, TimeUnit.MILLISECONDS); - checkCompletedNormally(f, 1); - } + CompletableFuture g = new CompletableFuture<>(); + long startTime = System.nanoTime(); + f.complete(v1); + assertSame(f, f.orTimeout(LONG_DELAY_MS, MILLISECONDS)); + assertSame(g, g.orTimeout(LONG_DELAY_MS, MILLISECONDS)); + g.complete(v1); + checkCompletedNormally(f, v1); + checkCompletedNormally(g, v1); + assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2); + }} /** - * completeOnTimeout completes with given value if not complete + * completeOnTimeout completes with given value if not complete */ - public void testCompleteOnTimeout() { - CompletableFuture f = new CompletableFuture<>(); - f.completeOnTimeout(-1, SHORT_DELAY_MS, TimeUnit.MILLISECONDS); - f.join(); - checkCompletedNormally(f, -1); + public void testCompleteOnTimeout_timesOut() { + testInParallel(() -> testCompleteOnTimeout_timesOut(42), + () -> testCompleteOnTimeout_timesOut(null)); } /** - * completeOnTimeout has no effect if completed within timeout + * completeOnTimeout completes with given value if not complete */ - public void testCompleteOnTimeout2() { + public void testCompleteOnTimeout_timesOut(Integer v) { + long timeoutMillis = timeoutMillis(); CompletableFuture f = new CompletableFuture<>(); - f.complete(1); - f.completeOnTimeout(-1, SHORT_DELAY_MS, TimeUnit.MILLISECONDS); - checkCompletedNormally(f, 1); + long startTime = System.nanoTime(); + assertSame(f, f.completeOnTimeout(v, timeoutMillis, MILLISECONDS)); + assertSame(v, f.join()); + assertTrue(millisElapsedSince(startTime) >= timeoutMillis); + f.complete(99); // should have no effect + checkCompletedNormally(f, v); } /** - * delayedExecutor returns an executor that delays submission + * completeOnTimeout has no effect if completed within timeout */ - public void testDelayedExecutor() { - long timeoutMillis = SMALL_DELAY_MS; - Executor d = CompletableFuture.delayedExecutor(timeoutMillis, - MILLISECONDS); + public void testCompleteOnTimeout_completed() { + for (Integer v1 : new Integer[] { 1, null }) + { + CompletableFuture f = new CompletableFuture<>(); + CompletableFuture g = new CompletableFuture<>(); long startTime = System.nanoTime(); - CompletableFuture f = CompletableFuture.supplyAsync(() -> 1, d); - assertNull(f.getNow(null)); - try { - f.get(LONG_DELAY_MS, MILLISECONDS); - } catch (Throwable fail) { threadUnexpectedException(fail); } - assertTrue(millisElapsedSince(startTime) > timeoutMillis/2); - checkCompletedNormally(f, 1); - } + f.complete(v1); + assertSame(f, f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS)); + assertSame(g, g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS)); + g.complete(v1); + checkCompletedNormally(f, v1); + checkCompletedNormally(g, v1); + assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2); + }} /** - * delayedExecutor for a given executor returns an executor that - * delays submission + * delayedExecutor returns an executor that delays submission */ - public void testDelayedExecutor2() { - long timeoutMillis = SMALL_DELAY_MS; - Executor d = CompletableFuture.delayedExecutor(timeoutMillis, - MILLISECONDS, - new ThreadExecutor()); + public void testDelayedExecutor() { + testInParallel(() -> testDelayedExecutor(null, null), + () -> testDelayedExecutor(null, 1), + () -> testDelayedExecutor(new ThreadExecutor(), 1), + () -> testDelayedExecutor(new ThreadExecutor(), 1)); + } + + public void testDelayedExecutor(Executor executor, Integer v) throws Exception { + long timeoutMillis = timeoutMillis(); + // Use an "unreasonably long" long timeout to catch lingering threads + long longTimeoutMillis = 1000 * 60 * 60 * 24; + final Executor delayer, longDelayer; + if (executor == null) { + delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS); + longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS); + } else { + delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor); + longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor); + } long startTime = System.nanoTime(); - CompletableFuture f = CompletableFuture.supplyAsync(() -> 1, d); - assertNull(f.getNow(null)); - try { - f.get(LONG_DELAY_MS, MILLISECONDS); - } catch (Throwable fail) { threadUnexpectedException(fail); } - assertTrue(millisElapsedSince(startTime) > timeoutMillis/2); - checkCompletedNormally(f, 1); + CompletableFuture f = + CompletableFuture.supplyAsync(() -> v, delayer); + CompletableFuture g = + CompletableFuture.supplyAsync(() -> v, longDelayer); + + assertNull(g.getNow(null)); + + assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS)); + long millisElapsed = millisElapsedSince(startTime); + assertTrue(millisElapsed >= timeoutMillis); + assertTrue(millisElapsed < LONG_DELAY_MS / 2); + + checkCompletedNormally(f, v); + + checkIncomplete(g); + assertTrue(g.cancel(true)); } //--- tests of implementation details; not part of official tck --- @@ -3652,7 +3663,7 @@ public class CompletableFutureTest exten funs.add((y) -> m.thenAcceptBoth(y, v42, new SubtractAction(m))); funs.add((y) -> m.thenCombine(y, v42, new SubtractFunction(m))); - funs.add((y) -> m.whenComplete(y, (Integer x, Throwable t) -> {})); + funs.add((y) -> m.whenComplete(y, (Integer r, Throwable t) -> {})); funs.add((y) -> m.thenCompose(y, new CompletableFutureInc(m))); @@ -3708,4 +3719,269 @@ public class CompletableFutureTest exten } }} + /** + * Minimal completion stages throw UOE for all non-CompletionStage methods + */ + public void testMinimalCompletionStage_minimality() { + if (!testImplementationDetails) return; + Function toSignature = + (method) -> method.getName() + Arrays.toString(method.getParameterTypes()); + Predicate isNotStatic = + (method) -> (method.getModifiers() & Modifier.STATIC) == 0; + List minimalMethods = + Stream.of(Object.class, CompletionStage.class) + .flatMap((klazz) -> Stream.of(klazz.getMethods())) + .filter(isNotStatic) + .collect(Collectors.toList()); + // Methods from CompletableFuture permitted NOT to throw UOE + String[] signatureWhitelist = { + "newIncompleteFuture[]", + "defaultExecutor[]", + "minimalCompletionStage[]", + "copy[]", + }; + Set permittedMethodSignatures = + Stream.concat(minimalMethods.stream().map(toSignature), + Stream.of(signatureWhitelist)) + .collect(Collectors.toSet()); + List allMethods = Stream.of(CompletableFuture.class.getMethods()) + .filter(isNotStatic) + .filter((method) -> !permittedMethodSignatures.contains(toSignature.apply(method))) + .collect(Collectors.toList()); + + CompletionStage minimalStage = + new CompletableFuture().minimalCompletionStage(); + + List bugs = new ArrayList<>(); + for (Method method : allMethods) { + Class[] parameterTypes = method.getParameterTypes(); + Object[] args = new Object[parameterTypes.length]; + // Manufacture boxed primitives for primitive params + for (int i = 0; i < args.length; i++) { + Class type = parameterTypes[i]; + if (parameterTypes[i] == boolean.class) + args[i] = false; + else if (parameterTypes[i] == int.class) + args[i] = 0; + else if (parameterTypes[i] == long.class) + args[i] = 0L; + } + try { + method.invoke(minimalStage, args); + bugs.add(method); + } + catch (java.lang.reflect.InvocationTargetException expected) { + if (! (expected.getCause() instanceof UnsupportedOperationException)) { + bugs.add(method); + // expected.getCause().printStackTrace(); + } + } + catch (ReflectiveOperationException bad) { throw new Error(bad); } + } + if (!bugs.isEmpty()) + throw new Error("Methods did not throw UOE: " + bugs.toString()); + } + + static class Monad { + static class ZeroException extends RuntimeException { + public ZeroException() { super("monadic zero"); } + } + // "return", "unit" + static CompletableFuture unit(T value) { + return completedFuture(value); + } + // monadic zero ? + static CompletableFuture zero() { + return failedFuture(new ZeroException()); + } + // >=> + static Function> compose + (Function> f, + Function> g) { + return (x) -> f.apply(x).thenCompose(g); + } + + static void assertZero(CompletableFuture f) { + try { + f.getNow(null); + throw new AssertionFailedError("should throw"); + } catch (CompletionException success) { + assertTrue(success.getCause() instanceof ZeroException); + } + } + + static void assertFutureEquals(CompletableFuture f, + CompletableFuture g) { + T fval = null, gval = null; + Throwable fex = null, gex = null; + + try { fval = f.get(); } + catch (ExecutionException ex) { fex = ex.getCause(); } + catch (Throwable ex) { fex = ex; } + + try { gval = g.get(); } + catch (ExecutionException ex) { gex = ex.getCause(); } + catch (Throwable ex) { gex = ex; } + + if (fex != null || gex != null) + assertSame(fex.getClass(), gex.getClass()); + else + assertEquals(fval, gval); + } + + static class PlusFuture extends CompletableFuture { + AtomicReference firstFailure = new AtomicReference<>(null); + } + + /** Implements "monadic plus". */ + static CompletableFuture plus(CompletableFuture f, + CompletableFuture g) { + PlusFuture plus = new PlusFuture(); + BiConsumer action = (T result, Throwable ex) -> { + try { + if (ex == null) { + if (plus.complete(result)) + if (plus.firstFailure.get() != null) + plus.firstFailure.set(null); + } + else if (plus.firstFailure.compareAndSet(null, ex)) { + if (plus.isDone()) + plus.firstFailure.set(null); + } + else { + // first failure has precedence + Throwable first = plus.firstFailure.getAndSet(null); + + // may fail with "Self-suppression not permitted" + try { first.addSuppressed(ex); } + catch (Exception ignored) {} + + plus.completeExceptionally(first); + } + } catch (Throwable unexpected) { + plus.completeExceptionally(unexpected); + } + }; + f.whenComplete(action); + g.whenComplete(action); + return plus; + } + } + + /** + * CompletableFuture is an additive monad - sort of. + * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads + */ + public void testAdditiveMonad() throws Throwable { + Function> unit = Monad::unit; + CompletableFuture zero = Monad.zero(); + + // Some mutually non-commutative functions + Function> triple + = (x) -> Monad.unit(3 * x); + Function> inc + = (x) -> Monad.unit(x + 1); + + // unit is a right identity: m >>= unit === m + Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit), + inc.apply(5L)); + // unit is a left identity: (unit x) >>= f === f x + Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc), + inc.apply(5L)); + + // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) ) + Monad.assertFutureEquals( + unit.apply(5L).thenCompose(inc).thenCompose(triple), + unit.apply(5L).thenCompose((x) -> inc.apply(x).thenCompose(triple))); + + // The case for CompletableFuture as an additive monad is weaker... + + // zero is a monadic zero + Monad.assertZero(zero); + + // left zero: zero >>= f === zero + Monad.assertZero(zero.thenCompose(inc)); + // right zero: f >>= (\x -> zero) === zero + Monad.assertZero(inc.apply(5L).thenCompose((x) -> zero)); + + // f plus zero === f + Monad.assertFutureEquals(Monad.unit(5L), + Monad.plus(Monad.unit(5L), zero)); + // zero plus f === f + Monad.assertFutureEquals(Monad.unit(5L), + Monad.plus(zero, Monad.unit(5L))); + // zero plus zero === zero + Monad.assertZero(Monad.plus(zero, zero)); + { + CompletableFuture f = Monad.plus(Monad.unit(5L), + Monad.unit(8L)); + // non-determinism + assertTrue(f.get() == 5L || f.get() == 8L); + } + + CompletableFuture godot = new CompletableFuture<>(); + // f plus godot === f (doesn't wait for godot) + Monad.assertFutureEquals(Monad.unit(5L), + Monad.plus(Monad.unit(5L), godot)); + // godot plus f === f (doesn't wait for godot) + Monad.assertFutureEquals(Monad.unit(5L), + Monad.plus(godot, Monad.unit(5L))); + } + + /** + * A single CompletableFuture with many dependents. + * A demo of scalability - runtime is O(n). + */ + public void testManyDependents() throws Throwable { + final int n = 1_000; + final CompletableFuture head = new CompletableFuture<>(); + final CompletableFuture complete = CompletableFuture.completedFuture((Void)null); + final AtomicInteger count = new AtomicInteger(0); + for (int i = 0; i < n; i++) { + head.thenRun(() -> count.getAndIncrement()); + head.thenAccept((x) -> count.getAndIncrement()); + head.thenApply((x) -> count.getAndIncrement()); + + head.runAfterBoth(complete, () -> count.getAndIncrement()); + head.thenAcceptBoth(complete, (x, y) -> count.getAndIncrement()); + head.thenCombine(complete, (x, y) -> count.getAndIncrement()); + complete.runAfterBoth(head, () -> count.getAndIncrement()); + complete.thenAcceptBoth(head, (x, y) -> count.getAndIncrement()); + complete.thenCombine(head, (x, y) -> count.getAndIncrement()); + + head.runAfterEither(new CompletableFuture(), () -> count.getAndIncrement()); + head.acceptEither(new CompletableFuture(), (x) -> count.getAndIncrement()); + head.applyToEither(new CompletableFuture(), (x) -> count.getAndIncrement()); + new CompletableFuture().runAfterEither(head, () -> count.getAndIncrement()); + new CompletableFuture().acceptEither(head, (x) -> count.getAndIncrement()); + new CompletableFuture().applyToEither(head, (x) -> count.getAndIncrement()); + } + head.complete(null); + assertEquals(5 * 3 * n, count.get()); + } + +// static U join(CompletionStage stage) { +// CompletableFuture f = new CompletableFuture<>(); +// stage.whenComplete((v, ex) -> { +// if (ex != null) f.completeExceptionally(ex); else f.complete(v); +// }); +// return f.join(); +// } + +// static boolean isDone(CompletionStage stage) { +// CompletableFuture f = new CompletableFuture<>(); +// stage.whenComplete((v, ex) -> { +// if (ex != null) f.completeExceptionally(ex); else f.complete(v); +// }); +// return f.isDone(); +// } + +// static U join2(CompletionStage stage) { +// return stage.toCompletableFuture().copy().join(); +// } + +// static boolean isDone2(CompletionStage stage) { +// return stage.toCompletableFuture().copy().isDone(); +// } + }