ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/CompletableFutureTest.java
Revision: 1.212
Committed: Mon Sep 24 17:04:26 2018 UTC (5 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.211: +0 -1 lines
Log Message:
whitespace

File Contents

# User Rev Content
1 jsr166 1.1 /*
2 jsr166 1.4 * Written by Doug Lea and Martin Buchholz with assistance from
3     * members of JCP JSR-166 Expert Group and released to the public
4     * domain, as explained at
5 jsr166 1.1 * http://creativecommons.org/publicdomain/zero/1.0/
6     */
7    
8 jsr166 1.98 import static java.util.concurrent.TimeUnit.MILLISECONDS;
9     import static java.util.concurrent.TimeUnit.SECONDS;
10 jsr166 1.128 import static java.util.concurrent.CompletableFuture.completedFuture;
11     import static java.util.concurrent.CompletableFuture.failedFuture;
12 jsr166 1.98
13 jsr166 1.123 import java.lang.reflect.Method;
14     import java.lang.reflect.Modifier;
15    
16     import java.util.stream.Collectors;
17     import java.util.stream.Stream;
18    
19 jsr166 1.98 import java.util.ArrayList;
20 jsr166 1.123 import java.util.Arrays;
21 jsr166 1.98 import java.util.List;
22     import java.util.Objects;
23 jsr166 1.123 import java.util.Set;
24 jsr166 1.1 import java.util.concurrent.Callable;
25     import java.util.concurrent.CancellationException;
26     import java.util.concurrent.CompletableFuture;
27 dl 1.5 import java.util.concurrent.CompletionException;
28 jsr166 1.35 import java.util.concurrent.CompletionStage;
29 jsr166 1.98 import java.util.concurrent.ExecutionException;
30     import java.util.concurrent.Executor;
31 jsr166 1.48 import java.util.concurrent.ForkJoinPool;
32     import java.util.concurrent.ForkJoinTask;
33 jsr166 1.152 import java.util.concurrent.RejectedExecutionException;
34 jsr166 1.1 import java.util.concurrent.TimeoutException;
35     import java.util.concurrent.atomic.AtomicInteger;
36 dl 1.103 import java.util.concurrent.atomic.AtomicReference;
37 jsr166 1.98 import java.util.function.BiConsumer;
38     import java.util.function.BiFunction;
39 dl 1.5 import java.util.function.Consumer;
40     import java.util.function.Function;
41 jsr166 1.124 import java.util.function.Predicate;
42 jsr166 1.98 import java.util.function.Supplier;
43    
44     import junit.framework.Test;
45     import junit.framework.TestSuite;
46 jsr166 1.1
47     public class CompletableFutureTest extends JSR166TestCase {
48    
49     public static void main(String[] args) {
50 jsr166 1.102 main(suite(), args);
51 jsr166 1.1 }
52     public static Test suite() {
53     return new TestSuite(CompletableFutureTest.class);
54     }
55    
56 dl 1.5 static class CFException extends RuntimeException {}
57    
58 jsr166 1.4 void checkIncomplete(CompletableFuture<?> f) {
59     assertFalse(f.isDone());
60     assertFalse(f.isCancelled());
61 jsr166 1.188 assertTrue(f.toString().matches(".*\\[.*Not completed.*\\]"));
62 jsr166 1.195
63     Object result = null;
64 jsr166 1.4 try {
65 jsr166 1.195 result = f.getNow(null);
66 jsr166 1.190 } catch (Throwable fail) { threadUnexpectedException(fail); }
67 jsr166 1.195 assertNull(result);
68    
69 jsr166 1.4 try {
70 jsr166 1.185 f.get(randomExpiredTimeout(), randomTimeUnit());
71 jsr166 1.4 shouldThrow();
72     }
73     catch (TimeoutException success) {}
74     catch (Throwable fail) { threadUnexpectedException(fail); }
75     }
76    
77 jsr166 1.197 <T> void checkCompletedNormally(CompletableFuture<T> f, T expectedValue) {
78     checkTimedGet(f, expectedValue);
79 jsr166 1.95
80 jsr166 1.197 assertEquals(expectedValue, f.join());
81     assertEquals(expectedValue, f.getNow(null));
82 jsr166 1.196
83     T result = null;
84 jsr166 1.20 try {
85 jsr166 1.196 result = f.get();
86 jsr166 1.190 } catch (Throwable fail) { threadUnexpectedException(fail); }
87 jsr166 1.197 assertEquals(expectedValue, result);
88 jsr166 1.196
89 dl 1.5 assertTrue(f.isDone());
90     assertFalse(f.isCancelled());
91 dl 1.26 assertFalse(f.isCompletedExceptionally());
92 jsr166 1.188 assertTrue(f.toString().matches(".*\\[.*Completed normally.*\\]"));
93 dl 1.5 }
94    
95 jsr166 1.121 /**
96     * Returns the "raw" internal exceptional completion of f,
97     * without any additional wrapping with CompletionException.
98     */
99 jsr166 1.182 Throwable exceptionalCompletion(CompletableFuture<?> f) {
100     // handle (and whenComplete and exceptionally) can distinguish
101     // between "direct" and "wrapped" exceptional completion
102     return f.handle((u, t) -> t).join();
103 jsr166 1.121 }
104    
105     void checkCompletedExceptionally(CompletableFuture<?> f,
106     boolean wrapped,
107     Consumer<Throwable> checker) {
108     Throwable cause = exceptionalCompletion(f);
109     if (wrapped) {
110     assertTrue(cause instanceof CompletionException);
111     cause = cause.getCause();
112     }
113     checker.accept(cause);
114    
115 jsr166 1.95 long startTime = System.nanoTime();
116 dl 1.5 try {
117 jsr166 1.121 f.get(LONG_DELAY_MS, MILLISECONDS);
118 jsr166 1.20 shouldThrow();
119     } catch (ExecutionException success) {
120 jsr166 1.121 assertSame(cause, success.getCause());
121 jsr166 1.20 } catch (Throwable fail) { threadUnexpectedException(fail); }
122 jsr166 1.121 assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
123 jsr166 1.95
124 jsr166 1.20 try {
125 dl 1.5 f.join();
126     shouldThrow();
127 jsr166 1.8 } catch (CompletionException success) {
128 jsr166 1.121 assertSame(cause, success.getCause());
129     } catch (Throwable fail) { threadUnexpectedException(fail); }
130    
131 dl 1.5 try {
132     f.getNow(null);
133     shouldThrow();
134 jsr166 1.8 } catch (CompletionException success) {
135 jsr166 1.121 assertSame(cause, success.getCause());
136 jsr166 1.8 } catch (Throwable fail) { threadUnexpectedException(fail); }
137 dl 1.5
138 jsr166 1.33 try {
139     f.get();
140     shouldThrow();
141     } catch (ExecutionException success) {
142 jsr166 1.121 assertSame(cause, success.getCause());
143 jsr166 1.33 } catch (Throwable fail) { threadUnexpectedException(fail); }
144 jsr166 1.73
145 jsr166 1.121 assertFalse(f.isCancelled());
146 jsr166 1.33 assertTrue(f.isDone());
147 jsr166 1.121 assertTrue(f.isCompletedExceptionally());
148 jsr166 1.188 assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
149 jsr166 1.33 }
150    
151 jsr166 1.121 void checkCompletedWithWrappedCFException(CompletableFuture<?> f) {
152     checkCompletedExceptionally(f, true,
153 jsr166 1.180 t -> assertTrue(t instanceof CFException));
154 jsr166 1.121 }
155 dl 1.103
156 jsr166 1.121 void checkCompletedWithWrappedCancellationException(CompletableFuture<?> f) {
157     checkCompletedExceptionally(f, true,
158 jsr166 1.180 t -> assertTrue(t instanceof CancellationException));
159 jsr166 1.121 }
160 dl 1.103
161 jsr166 1.121 void checkCompletedWithTimeoutException(CompletableFuture<?> f) {
162     checkCompletedExceptionally(f, false,
163 jsr166 1.180 t -> assertTrue(t instanceof TimeoutException));
164 dl 1.103 }
165    
166 jsr166 1.121 void checkCompletedWithWrappedException(CompletableFuture<?> f,
167     Throwable ex) {
168 jsr166 1.180 checkCompletedExceptionally(f, true, t -> assertSame(t, ex));
169 jsr166 1.72 }
170    
171 jsr166 1.121 void checkCompletedExceptionally(CompletableFuture<?> f, Throwable ex) {
172 jsr166 1.180 checkCompletedExceptionally(f, false, t -> assertSame(t, ex));
173 jsr166 1.72 }
174    
175 dl 1.5 void checkCancelled(CompletableFuture<?> f) {
176 jsr166 1.95 long startTime = System.nanoTime();
177 dl 1.5 try {
178 jsr166 1.121 f.get(LONG_DELAY_MS, MILLISECONDS);
179 jsr166 1.20 shouldThrow();
180     } catch (CancellationException success) {
181     } catch (Throwable fail) { threadUnexpectedException(fail); }
182 jsr166 1.121 assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
183 jsr166 1.95
184 jsr166 1.20 try {
185 dl 1.5 f.join();
186     shouldThrow();
187 jsr166 1.8 } catch (CancellationException success) {}
188 dl 1.5 try {
189     f.getNow(null);
190     shouldThrow();
191 jsr166 1.8 } catch (CancellationException success) {}
192 dl 1.5 try {
193     f.get();
194     shouldThrow();
195 jsr166 1.8 } catch (CancellationException success) {
196     } catch (Throwable fail) { threadUnexpectedException(fail); }
197 dl 1.5
198 jsr166 1.121 assertTrue(exceptionalCompletion(f) instanceof CancellationException);
199 jsr166 1.95
200 dl 1.5 assertTrue(f.isDone());
201 dl 1.26 assertTrue(f.isCompletedExceptionally());
202 jsr166 1.121 assertTrue(f.isCancelled());
203 jsr166 1.188 assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
204 dl 1.5 }
205    
206     /**
207     * A newly constructed CompletableFuture is incomplete, as indicated
208     * by methods isDone, isCancelled, and getNow
209     */
210     public void testConstructor() {
211 jsr166 1.22 CompletableFuture<Integer> f = new CompletableFuture<>();
212 dl 1.5 checkIncomplete(f);
213     }
214    
215     /**
216     * complete completes normally, as indicated by methods isDone,
217     * isCancelled, join, get, and getNow
218     */
219     public void testComplete() {
220 jsr166 1.78 for (Integer v1 : new Integer[] { 1, null })
221     {
222 jsr166 1.22 CompletableFuture<Integer> f = new CompletableFuture<>();
223 dl 1.5 checkIncomplete(f);
224 jsr166 1.78 assertTrue(f.complete(v1));
225     assertFalse(f.complete(v1));
226     checkCompletedNormally(f, v1);
227     }}
228 dl 1.5
229     /**
230     * completeExceptionally completes exceptionally, as indicated by
231     * methods isDone, isCancelled, join, get, and getNow
232     */
233     public void testCompleteExceptionally() {
234 jsr166 1.22 CompletableFuture<Integer> f = new CompletableFuture<>();
235 jsr166 1.72 CFException ex = new CFException();
236 dl 1.5 checkIncomplete(f);
237 jsr166 1.72 f.completeExceptionally(ex);
238     checkCompletedExceptionally(f, ex);
239 dl 1.5 }
240    
241     /**
242     * cancel completes exceptionally and reports cancelled, as indicated by
243     * methods isDone, isCancelled, join, get, and getNow
244     */
245     public void testCancel() {
246 jsr166 1.78 for (boolean mayInterruptIfRunning : new boolean[] { true, false })
247     {
248 jsr166 1.22 CompletableFuture<Integer> f = new CompletableFuture<>();
249 dl 1.5 checkIncomplete(f);
250 jsr166 1.101 assertTrue(f.cancel(mayInterruptIfRunning));
251     assertTrue(f.cancel(mayInterruptIfRunning));
252     assertTrue(f.cancel(!mayInterruptIfRunning));
253 dl 1.5 checkCancelled(f);
254 jsr166 1.78 }}
255 dl 1.5
256     /**
257     * obtrudeValue forces completion with given value
258     */
259     public void testObtrudeValue() {
260 jsr166 1.22 CompletableFuture<Integer> f = new CompletableFuture<>();
261 dl 1.5 checkIncomplete(f);
262 jsr166 1.78 assertTrue(f.complete(one));
263 dl 1.5 checkCompletedNormally(f, one);
264     f.obtrudeValue(three);
265     checkCompletedNormally(f, three);
266     f.obtrudeValue(two);
267     checkCompletedNormally(f, two);
268 jsr166 1.22 f = new CompletableFuture<>();
269 dl 1.5 f.obtrudeValue(three);
270     checkCompletedNormally(f, three);
271 jsr166 1.46 f.obtrudeValue(null);
272     checkCompletedNormally(f, null);
273 jsr166 1.22 f = new CompletableFuture<>();
274 dl 1.5 f.completeExceptionally(new CFException());
275     f.obtrudeValue(four);
276     checkCompletedNormally(f, four);
277 jsr166 1.4 }
278    
279 dl 1.5 /**
280     * obtrudeException forces completion with given exception
281     */
282     public void testObtrudeException() {
283 jsr166 1.72 for (Integer v1 : new Integer[] { 1, null })
284     {
285     CFException ex;
286     CompletableFuture<Integer> f;
287    
288     f = new CompletableFuture<>();
289 jsr166 1.78 assertTrue(f.complete(v1));
290 jsr166 1.72 for (int i = 0; i < 2; i++) {
291     f.obtrudeException(ex = new CFException());
292     checkCompletedExceptionally(f, ex);
293     }
294    
295 jsr166 1.22 f = new CompletableFuture<>();
296 jsr166 1.72 for (int i = 0; i < 2; i++) {
297     f.obtrudeException(ex = new CFException());
298     checkCompletedExceptionally(f, ex);
299     }
300    
301 jsr166 1.22 f = new CompletableFuture<>();
302 jsr166 1.193 f.completeExceptionally(new CFException());
303 jsr166 1.72 f.obtrudeValue(v1);
304     checkCompletedNormally(f, v1);
305     f.obtrudeException(ex = new CFException());
306     checkCompletedExceptionally(f, ex);
307 dl 1.5 f.completeExceptionally(new CFException());
308 jsr166 1.72 checkCompletedExceptionally(f, ex);
309 jsr166 1.78 assertFalse(f.complete(v1));
310 jsr166 1.72 checkCompletedExceptionally(f, ex);
311     }}
312 jsr166 1.6
313 dl 1.5 /**
314     * getNumberOfDependents returns number of dependent tasks
315     */
316     public void testGetNumberOfDependents() {
317 jsr166 1.76 for (ExecutionMode m : ExecutionMode.values())
318 jsr166 1.78 for (Integer v1 : new Integer[] { 1, null })
319 jsr166 1.76 {
320 jsr166 1.22 CompletableFuture<Integer> f = new CompletableFuture<>();
321 jsr166 1.46 assertEquals(0, f.getNumberOfDependents());
322 jsr166 1.76 final CompletableFuture<Void> g = m.thenRun(f, new Noop(m));
323 jsr166 1.46 assertEquals(1, f.getNumberOfDependents());
324     assertEquals(0, g.getNumberOfDependents());
325 jsr166 1.76 final CompletableFuture<Void> h = m.thenRun(f, new Noop(m));
326 jsr166 1.46 assertEquals(2, f.getNumberOfDependents());
327 jsr166 1.76 assertEquals(0, h.getNumberOfDependents());
328 jsr166 1.78 assertTrue(f.complete(v1));
329 dl 1.5 checkCompletedNormally(g, null);
330 jsr166 1.76 checkCompletedNormally(h, null);
331 jsr166 1.46 assertEquals(0, f.getNumberOfDependents());
332     assertEquals(0, g.getNumberOfDependents());
333 jsr166 1.76 assertEquals(0, h.getNumberOfDependents());
334     }}
335 jsr166 1.3
336 dl 1.5 /**
337     * toString indicates current completion state
338     */
339 jsr166 1.188 public void testToString_incomplete() {
340 jsr166 1.191 CompletableFuture<String> f = new CompletableFuture<>();
341 jsr166 1.188 assertTrue(f.toString().matches(".*\\[.*Not completed.*\\]"));
342     if (testImplementationDetails)
343     assertEquals(identityString(f) + "[Not completed]",
344     f.toString());
345     }
346 jsr166 1.2
347 jsr166 1.188 public void testToString_normal() {
348 jsr166 1.191 CompletableFuture<String> f = new CompletableFuture<>();
349 jsr166 1.78 assertTrue(f.complete("foo"));
350 jsr166 1.188 assertTrue(f.toString().matches(".*\\[.*Completed normally.*\\]"));
351     if (testImplementationDetails)
352     assertEquals(identityString(f) + "[Completed normally]",
353     f.toString());
354     }
355 jsr166 1.2
356 jsr166 1.188 public void testToString_exception() {
357 jsr166 1.191 CompletableFuture<String> f = new CompletableFuture<>();
358 jsr166 1.78 assertTrue(f.completeExceptionally(new IndexOutOfBoundsException()));
359 jsr166 1.188 assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
360     if (testImplementationDetails)
361     assertTrue(f.toString().startsWith(
362     identityString(f) + "[Completed exceptionally: "));
363     }
364 jsr166 1.74
365 jsr166 1.188 public void testToString_cancelled() {
366 jsr166 1.77 for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
367 jsr166 1.191 CompletableFuture<String> f = new CompletableFuture<>();
368 jsr166 1.78 assertTrue(f.cancel(mayInterruptIfRunning));
369 jsr166 1.188 assertTrue(f.toString().matches(".*\\[.*Completed exceptionally.*\\]"));
370     if (testImplementationDetails)
371     assertTrue(f.toString().startsWith(
372     identityString(f) + "[Completed exceptionally: "));
373 jsr166 1.77 }
374 jsr166 1.1 }
375 jsr166 1.4
376 dl 1.9 /**
377 jsr166 1.10 * completedFuture returns a completed CompletableFuture with given value
378 dl 1.9 */
379     public void testCompletedFuture() {
380     CompletableFuture<String> f = CompletableFuture.completedFuture("test");
381     checkCompletedNormally(f, "test");
382     }
383    
384 jsr166 1.172 abstract static class CheckedAction {
385 jsr166 1.62 int invocationCount = 0;
386 jsr166 1.58 final ExecutionMode m;
387 jsr166 1.62 CheckedAction(ExecutionMode m) { this.m = m; }
388     void invoked() {
389     m.checkExecutionMode();
390     assertEquals(0, invocationCount++);
391     }
392     void assertNotInvoked() { assertEquals(0, invocationCount); }
393     void assertInvoked() { assertEquals(1, invocationCount); }
394     }
395    
396 jsr166 1.172 abstract static class CheckedIntegerAction extends CheckedAction {
397 jsr166 1.62 Integer value;
398     CheckedIntegerAction(ExecutionMode m) { super(m); }
399     void assertValue(Integer expected) {
400     assertInvoked();
401     assertEquals(expected, value);
402     }
403     }
404    
405 jsr166 1.172 static class IntegerSupplier extends CheckedAction
406 jsr166 1.62 implements Supplier<Integer>
407     {
408 jsr166 1.58 final Integer value;
409     IntegerSupplier(ExecutionMode m, Integer value) {
410 jsr166 1.62 super(m);
411 jsr166 1.58 this.value = value;
412     }
413     public Integer get() {
414 jsr166 1.62 invoked();
415 jsr166 1.58 return value;
416     }
417     }
418 jsr166 1.60
419     // A function that handles and produces null values as well.
420     static Integer inc(Integer x) {
421     return (x == null) ? null : x + 1;
422     }
423    
424 jsr166 1.172 static class NoopConsumer extends CheckedIntegerAction
425 jsr166 1.62 implements Consumer<Integer>
426     {
427 jsr166 1.64 NoopConsumer(ExecutionMode m) { super(m); }
428 jsr166 1.38 public void accept(Integer x) {
429 jsr166 1.62 invoked();
430 jsr166 1.64 value = x;
431 jsr166 1.38 }
432     }
433 jsr166 1.62
434 jsr166 1.172 static class IncFunction extends CheckedIntegerAction
435 jsr166 1.62 implements Function<Integer,Integer>
436     {
437     IncFunction(ExecutionMode m) { super(m); }
438 jsr166 1.38 public Integer apply(Integer x) {
439 jsr166 1.62 invoked();
440 jsr166 1.38 return value = inc(x);
441     }
442 dl 1.5 }
443 jsr166 1.60
444     // Choose non-commutative actions for better coverage
445     // A non-commutative function that handles and produces null values as well.
446     static Integer subtract(Integer x, Integer y) {
447     return (x == null && y == null) ? null :
448     ((x == null) ? 42 : x.intValue())
449     - ((y == null) ? 99 : y.intValue());
450     }
451    
452 jsr166 1.172 static class SubtractAction extends CheckedIntegerAction
453 jsr166 1.62 implements BiConsumer<Integer, Integer>
454     {
455     SubtractAction(ExecutionMode m) { super(m); }
456 jsr166 1.6 public void accept(Integer x, Integer y) {
457 jsr166 1.62 invoked();
458 jsr166 1.35 value = subtract(x, y);
459 dl 1.5 }
460     }
461 jsr166 1.62
462 jsr166 1.172 static class SubtractFunction extends CheckedIntegerAction
463 jsr166 1.62 implements BiFunction<Integer, Integer, Integer>
464     {
465     SubtractFunction(ExecutionMode m) { super(m); }
466 jsr166 1.36 public Integer apply(Integer x, Integer y) {
467 jsr166 1.62 invoked();
468 jsr166 1.37 return value = subtract(x, y);
469 jsr166 1.36 }
470     }
471 jsr166 1.60
472 jsr166 1.172 static class Noop extends CheckedAction implements Runnable {
473 jsr166 1.62 Noop(ExecutionMode m) { super(m); }
474 jsr166 1.41 public void run() {
475 jsr166 1.62 invoked();
476 jsr166 1.41 }
477 dl 1.5 }
478    
479 jsr166 1.172 static class FailingSupplier extends CheckedAction
480 jsr166 1.63 implements Supplier<Integer>
481 jsr166 1.62 {
482 jsr166 1.151 final CFException ex;
483     FailingSupplier(ExecutionMode m) { super(m); ex = new CFException(); }
484 jsr166 1.44 public Integer get() {
485 jsr166 1.62 invoked();
486 jsr166 1.151 throw ex;
487 jsr166 1.44 }
488 dl 1.5 }
489 jsr166 1.62
490 jsr166 1.172 static class FailingConsumer extends CheckedIntegerAction
491 jsr166 1.63 implements Consumer<Integer>
492     {
493 jsr166 1.151 final CFException ex;
494     FailingConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
495 jsr166 1.44 public void accept(Integer x) {
496 jsr166 1.62 invoked();
497 jsr166 1.63 value = x;
498 jsr166 1.151 throw ex;
499 jsr166 1.44 }
500 dl 1.5 }
501 jsr166 1.62
502 jsr166 1.172 static class FailingBiConsumer extends CheckedIntegerAction
503 jsr166 1.62 implements BiConsumer<Integer, Integer>
504     {
505 jsr166 1.151 final CFException ex;
506     FailingBiConsumer(ExecutionMode m) { super(m); ex = new CFException(); }
507 jsr166 1.44 public void accept(Integer x, Integer y) {
508 jsr166 1.62 invoked();
509 jsr166 1.63 value = subtract(x, y);
510 jsr166 1.151 throw ex;
511 jsr166 1.44 }
512 dl 1.5 }
513 jsr166 1.62
514 jsr166 1.172 static class FailingFunction extends CheckedIntegerAction
515 jsr166 1.62 implements Function<Integer, Integer>
516     {
517 jsr166 1.151 final CFException ex;
518     FailingFunction(ExecutionMode m) { super(m); ex = new CFException(); }
519 jsr166 1.44 public Integer apply(Integer x) {
520 jsr166 1.62 invoked();
521 jsr166 1.63 value = x;
522 jsr166 1.151 throw ex;
523 jsr166 1.44 }
524 dl 1.5 }
525 jsr166 1.62
526 jsr166 1.172 static class FailingBiFunction extends CheckedIntegerAction
527 jsr166 1.62 implements BiFunction<Integer, Integer, Integer>
528     {
529 jsr166 1.151 final CFException ex;
530     FailingBiFunction(ExecutionMode m) { super(m); ex = new CFException(); }
531 jsr166 1.44 public Integer apply(Integer x, Integer y) {
532 jsr166 1.62 invoked();
533 jsr166 1.63 value = subtract(x, y);
534 jsr166 1.151 throw ex;
535 jsr166 1.44 }
536 dl 1.5 }
537 jsr166 1.62
538 jsr166 1.172 static class FailingRunnable extends CheckedAction implements Runnable {
539 jsr166 1.151 final CFException ex;
540     FailingRunnable(ExecutionMode m) { super(m); ex = new CFException(); }
541 jsr166 1.44 public void run() {
542 jsr166 1.62 invoked();
543 jsr166 1.151 throw ex;
544 jsr166 1.44 }
545 dl 1.5 }
546    
547 jsr166 1.172 static class CompletableFutureInc extends CheckedIntegerAction
548 jsr166 1.62 implements Function<Integer, CompletableFuture<Integer>>
549     {
550     CompletableFutureInc(ExecutionMode m) { super(m); }
551 dl 1.5 public CompletableFuture<Integer> apply(Integer x) {
552 jsr166 1.62 invoked();
553 jsr166 1.63 value = x;
554 jsr166 1.203 return CompletableFuture.completedFuture(inc(x));
555 dl 1.5 }
556     }
557    
558 dl 1.198 static class FailingExceptionalCompletableFutureFunction extends CheckedAction
559     implements Function<Throwable, CompletableFuture<Integer>>
560     {
561     final CFException ex;
562     FailingExceptionalCompletableFutureFunction(ExecutionMode m) { super(m); ex = new CFException(); }
563     public CompletableFuture<Integer> apply(Throwable x) {
564     invoked();
565     throw ex;
566     }
567     }
568    
569     static class ExceptionalCompletableFutureFunction extends CheckedAction
570     implements Function<Throwable, CompletionStage<Integer>> {
571     final Integer value = 3;
572     ExceptionalCompletableFutureFunction(ExecutionMode m) { super(m); }
573     public CompletionStage<Integer> apply(Throwable x) {
574     invoked();
575 jsr166 1.202 return CompletableFuture.completedFuture(value);
576 dl 1.198 }
577     }
578    
579 jsr166 1.172 static class FailingCompletableFutureFunction extends CheckedIntegerAction
580 jsr166 1.62 implements Function<Integer, CompletableFuture<Integer>>
581     {
582 jsr166 1.151 final CFException ex;
583     FailingCompletableFutureFunction(ExecutionMode m) { super(m); ex = new CFException(); }
584 dl 1.5 public CompletableFuture<Integer> apply(Integer x) {
585 jsr166 1.62 invoked();
586 jsr166 1.63 value = x;
587 jsr166 1.151 throw ex;
588 dl 1.5 }
589     }
590 jsr166 1.6
591 jsr166 1.155 static class CountingRejectingExecutor implements Executor {
592     final RejectedExecutionException ex = new RejectedExecutionException();
593     final AtomicInteger count = new AtomicInteger(0);
594     public void execute(Runnable r) {
595     count.getAndIncrement();
596     throw ex;
597     }
598     }
599    
600 dl 1.5 // Used for explicit executor tests
601     static final class ThreadExecutor implements Executor {
602 jsr166 1.56 final AtomicInteger count = new AtomicInteger(0);
603     static final ThreadGroup tg = new ThreadGroup("ThreadExecutor");
604     static boolean startedCurrentThread() {
605     return Thread.currentThread().getThreadGroup() == tg;
606     }
607 jsr166 1.17
608 dl 1.5 public void execute(Runnable r) {
609 jsr166 1.17 count.getAndIncrement();
610 jsr166 1.56 new Thread(tg, r).start();
611 dl 1.5 }
612     }
613    
614 jsr166 1.96 static final boolean defaultExecutorIsCommonPool
615     = ForkJoinPool.getCommonPoolParallelism() > 1;
616    
617 dl 1.5 /**
618 jsr166 1.35 * Permits the testing of parallel code for the 3 different
619 jsr166 1.60 * execution modes without copy/pasting all the test methods.
620 jsr166 1.35 */
621     enum ExecutionMode {
622 jsr166 1.95 SYNC {
623 jsr166 1.48 public void checkExecutionMode() {
624 jsr166 1.60 assertFalse(ThreadExecutor.startedCurrentThread());
625 jsr166 1.48 assertNull(ForkJoinTask.getPool());
626     }
627 jsr166 1.57 public CompletableFuture<Void> runAsync(Runnable a) {
628     throw new UnsupportedOperationException();
629     }
630 jsr166 1.58 public <U> CompletableFuture<U> supplyAsync(Supplier<U> a) {
631     throw new UnsupportedOperationException();
632     }
633 jsr166 1.46 public <T> CompletableFuture<Void> thenRun
634     (CompletableFuture<T> f, Runnable a) {
635     return f.thenRun(a);
636     }
637     public <T> CompletableFuture<Void> thenAccept
638     (CompletableFuture<T> f, Consumer<? super T> a) {
639     return f.thenAccept(a);
640     }
641     public <T,U> CompletableFuture<U> thenApply
642     (CompletableFuture<T> f, Function<? super T,U> a) {
643     return f.thenApply(a);
644     }
645     public <T,U> CompletableFuture<U> thenCompose
646     (CompletableFuture<T> f,
647     Function<? super T,? extends CompletionStage<U>> a) {
648     return f.thenCompose(a);
649     }
650     public <T,U> CompletableFuture<U> handle
651     (CompletableFuture<T> f,
652     BiFunction<? super T,Throwable,? extends U> a) {
653     return f.handle(a);
654     }
655     public <T> CompletableFuture<T> whenComplete
656     (CompletableFuture<T> f,
657     BiConsumer<? super T,? super Throwable> a) {
658     return f.whenComplete(a);
659     }
660 jsr166 1.35 public <T,U> CompletableFuture<Void> runAfterBoth
661     (CompletableFuture<T> f, CompletableFuture<U> g, Runnable a) {
662     return f.runAfterBoth(g, a);
663     }
664     public <T,U> CompletableFuture<Void> thenAcceptBoth
665     (CompletableFuture<T> f,
666     CompletionStage<? extends U> g,
667     BiConsumer<? super T,? super U> a) {
668     return f.thenAcceptBoth(g, a);
669     }
670 jsr166 1.36 public <T,U,V> CompletableFuture<V> thenCombine
671     (CompletableFuture<T> f,
672     CompletionStage<? extends U> g,
673     BiFunction<? super T,? super U,? extends V> a) {
674     return f.thenCombine(g, a);
675     }
676 jsr166 1.46 public <T> CompletableFuture<Void> runAfterEither
677 jsr166 1.38 (CompletableFuture<T> f,
678 jsr166 1.46 CompletionStage<?> g,
679     java.lang.Runnable a) {
680     return f.runAfterEither(g, a);
681 jsr166 1.38 }
682     public <T> CompletableFuture<Void> acceptEither
683     (CompletableFuture<T> f,
684     CompletionStage<? extends T> g,
685     Consumer<? super T> a) {
686     return f.acceptEither(g, a);
687     }
688 jsr166 1.46 public <T,U> CompletableFuture<U> applyToEither
689 jsr166 1.38 (CompletableFuture<T> f,
690 jsr166 1.46 CompletionStage<? extends T> g,
691     Function<? super T,U> a) {
692     return f.applyToEither(g, a);
693     }
694 dl 1.198 public <T> CompletableFuture<T> exceptionally
695     (CompletableFuture<T> f,
696     Function<Throwable, ? extends T> fn) {
697     return f.exceptionally(fn);
698     }
699     public <T> CompletableFuture<T> exceptionallyCompose
700     (CompletableFuture<T> f, Function<Throwable, ? extends CompletionStage<T>> fn) {
701     return f.exceptionallyCompose(fn);
702     }
703 jsr166 1.46 },
704 jsr166 1.48 ASYNC {
705     public void checkExecutionMode() {
706 jsr166 1.144 assertEquals(defaultExecutorIsCommonPool,
707     (ForkJoinPool.commonPool() == ForkJoinTask.getPool()));
708 jsr166 1.48 }
709 jsr166 1.57 public CompletableFuture<Void> runAsync(Runnable a) {
710     return CompletableFuture.runAsync(a);
711     }
712 jsr166 1.58 public <U> CompletableFuture<U> supplyAsync(Supplier<U> a) {
713     return CompletableFuture.supplyAsync(a);
714     }
715 jsr166 1.46 public <T> CompletableFuture<Void> thenRun
716     (CompletableFuture<T> f, Runnable a) {
717     return f.thenRunAsync(a);
718     }
719     public <T> CompletableFuture<Void> thenAccept
720     (CompletableFuture<T> f, Consumer<? super T> a) {
721     return f.thenAcceptAsync(a);
722     }
723     public <T,U> CompletableFuture<U> thenApply
724     (CompletableFuture<T> f, Function<? super T,U> a) {
725     return f.thenApplyAsync(a);
726 jsr166 1.38 }
727     public <T,U> CompletableFuture<U> thenCompose
728     (CompletableFuture<T> f,
729     Function<? super T,? extends CompletionStage<U>> a) {
730 jsr166 1.46 return f.thenComposeAsync(a);
731     }
732     public <T,U> CompletableFuture<U> handle
733     (CompletableFuture<T> f,
734     BiFunction<? super T,Throwable,? extends U> a) {
735     return f.handleAsync(a);
736 jsr166 1.38 }
737     public <T> CompletableFuture<T> whenComplete
738     (CompletableFuture<T> f,
739     BiConsumer<? super T,? super Throwable> a) {
740 jsr166 1.46 return f.whenCompleteAsync(a);
741 jsr166 1.38 }
742 jsr166 1.35 public <T,U> CompletableFuture<Void> runAfterBoth
743     (CompletableFuture<T> f, CompletableFuture<U> g, Runnable a) {
744     return f.runAfterBothAsync(g, a);
745     }
746     public <T,U> CompletableFuture<Void> thenAcceptBoth
747     (CompletableFuture<T> f,
748     CompletionStage<? extends U> g,
749     BiConsumer<? super T,? super U> a) {
750     return f.thenAcceptBothAsync(g, a);
751     }
752 jsr166 1.36 public <T,U,V> CompletableFuture<V> thenCombine
753     (CompletableFuture<T> f,
754     CompletionStage<? extends U> g,
755     BiFunction<? super T,? super U,? extends V> a) {
756     return f.thenCombineAsync(g, a);
757     }
758 jsr166 1.46 public <T> CompletableFuture<Void> runAfterEither
759 jsr166 1.38 (CompletableFuture<T> f,
760 jsr166 1.46 CompletionStage<?> g,
761     java.lang.Runnable a) {
762     return f.runAfterEitherAsync(g, a);
763 jsr166 1.38 }
764     public <T> CompletableFuture<Void> acceptEither
765     (CompletableFuture<T> f,
766     CompletionStage<? extends T> g,
767     Consumer<? super T> a) {
768     return f.acceptEitherAsync(g, a);
769     }
770 jsr166 1.46 public <T,U> CompletableFuture<U> applyToEither
771 jsr166 1.38 (CompletableFuture<T> f,
772 jsr166 1.46 CompletionStage<? extends T> g,
773     Function<? super T,U> a) {
774     return f.applyToEitherAsync(g, a);
775     }
776 dl 1.198 public <T> CompletableFuture<T> exceptionally
777     (CompletableFuture<T> f,
778     Function<Throwable, ? extends T> fn) {
779     return f.exceptionallyAsync(fn);
780     }
781    
782     public <T> CompletableFuture<T> exceptionallyCompose
783     (CompletableFuture<T> f, Function<Throwable, ? extends CompletionStage<T>> fn) {
784     return f.exceptionallyComposeAsync(fn);
785     }
786    
787 jsr166 1.46 },
788    
789     EXECUTOR {
790 jsr166 1.48 public void checkExecutionMode() {
791 jsr166 1.56 assertTrue(ThreadExecutor.startedCurrentThread());
792 jsr166 1.48 }
793 jsr166 1.57 public CompletableFuture<Void> runAsync(Runnable a) {
794     return CompletableFuture.runAsync(a, new ThreadExecutor());
795     }
796 jsr166 1.58 public <U> CompletableFuture<U> supplyAsync(Supplier<U> a) {
797     return CompletableFuture.supplyAsync(a, new ThreadExecutor());
798     }
799 jsr166 1.46 public <T> CompletableFuture<Void> thenRun
800     (CompletableFuture<T> f, Runnable a) {
801     return f.thenRunAsync(a, new ThreadExecutor());
802     }
803     public <T> CompletableFuture<Void> thenAccept
804     (CompletableFuture<T> f, Consumer<? super T> a) {
805     return f.thenAcceptAsync(a, new ThreadExecutor());
806     }
807     public <T,U> CompletableFuture<U> thenApply
808     (CompletableFuture<T> f, Function<? super T,U> a) {
809     return f.thenApplyAsync(a, new ThreadExecutor());
810 jsr166 1.38 }
811     public <T,U> CompletableFuture<U> thenCompose
812     (CompletableFuture<T> f,
813     Function<? super T,? extends CompletionStage<U>> a) {
814 jsr166 1.46 return f.thenComposeAsync(a, new ThreadExecutor());
815     }
816     public <T,U> CompletableFuture<U> handle
817     (CompletableFuture<T> f,
818     BiFunction<? super T,Throwable,? extends U> a) {
819     return f.handleAsync(a, new ThreadExecutor());
820 jsr166 1.38 }
821     public <T> CompletableFuture<T> whenComplete
822     (CompletableFuture<T> f,
823     BiConsumer<? super T,? super Throwable> a) {
824 jsr166 1.46 return f.whenCompleteAsync(a, new ThreadExecutor());
825 jsr166 1.38 }
826 jsr166 1.35 public <T,U> CompletableFuture<Void> runAfterBoth
827     (CompletableFuture<T> f, CompletableFuture<U> g, Runnable a) {
828     return f.runAfterBothAsync(g, a, new ThreadExecutor());
829     }
830     public <T,U> CompletableFuture<Void> thenAcceptBoth
831     (CompletableFuture<T> f,
832     CompletionStage<? extends U> g,
833     BiConsumer<? super T,? super U> a) {
834     return f.thenAcceptBothAsync(g, a, new ThreadExecutor());
835     }
836 jsr166 1.36 public <T,U,V> CompletableFuture<V> thenCombine
837     (CompletableFuture<T> f,
838     CompletionStage<? extends U> g,
839     BiFunction<? super T,? super U,? extends V> a) {
840     return f.thenCombineAsync(g, a, new ThreadExecutor());
841     }
842 jsr166 1.46 public <T> CompletableFuture<Void> runAfterEither
843 jsr166 1.38 (CompletableFuture<T> f,
844 jsr166 1.46 CompletionStage<?> g,
845     java.lang.Runnable a) {
846     return f.runAfterEitherAsync(g, a, new ThreadExecutor());
847 jsr166 1.38 }
848     public <T> CompletableFuture<Void> acceptEither
849     (CompletableFuture<T> f,
850     CompletionStage<? extends T> g,
851     Consumer<? super T> a) {
852     return f.acceptEitherAsync(g, a, new ThreadExecutor());
853     }
854 jsr166 1.46 public <T,U> CompletableFuture<U> applyToEither
855 jsr166 1.38 (CompletableFuture<T> f,
856 jsr166 1.46 CompletionStage<? extends T> g,
857     Function<? super T,U> a) {
858     return f.applyToEitherAsync(g, a, new ThreadExecutor());
859 jsr166 1.38 }
860 dl 1.198 public <T> CompletableFuture<T> exceptionally
861     (CompletableFuture<T> f,
862     Function<Throwable, ? extends T> fn) {
863     return f.exceptionallyAsync(fn, new ThreadExecutor());
864     }
865     public <T> CompletableFuture<T> exceptionallyCompose
866     (CompletableFuture<T> f, Function<Throwable, ? extends CompletionStage<T>> fn) {
867     return f.exceptionallyComposeAsync(fn, new ThreadExecutor());
868     }
869    
870 jsr166 1.35 };
871    
872 jsr166 1.48 public abstract void checkExecutionMode();
873 jsr166 1.57 public abstract CompletableFuture<Void> runAsync(Runnable a);
874 jsr166 1.58 public abstract <U> CompletableFuture<U> supplyAsync(Supplier<U> a);
875 jsr166 1.46 public abstract <T> CompletableFuture<Void> thenRun
876     (CompletableFuture<T> f, Runnable a);
877     public abstract <T> CompletableFuture<Void> thenAccept
878     (CompletableFuture<T> f, Consumer<? super T> a);
879     public abstract <T,U> CompletableFuture<U> thenApply
880     (CompletableFuture<T> f, Function<? super T,U> a);
881     public abstract <T,U> CompletableFuture<U> thenCompose
882     (CompletableFuture<T> f,
883     Function<? super T,? extends CompletionStage<U>> a);
884     public abstract <T,U> CompletableFuture<U> handle
885     (CompletableFuture<T> f,
886     BiFunction<? super T,Throwable,? extends U> a);
887     public abstract <T> CompletableFuture<T> whenComplete
888     (CompletableFuture<T> f,
889     BiConsumer<? super T,? super Throwable> a);
890 jsr166 1.35 public abstract <T,U> CompletableFuture<Void> runAfterBoth
891     (CompletableFuture<T> f, CompletableFuture<U> g, Runnable a);
892     public abstract <T,U> CompletableFuture<Void> thenAcceptBoth
893     (CompletableFuture<T> f,
894     CompletionStage<? extends U> g,
895     BiConsumer<? super T,? super U> a);
896 jsr166 1.36 public abstract <T,U,V> CompletableFuture<V> thenCombine
897     (CompletableFuture<T> f,
898     CompletionStage<? extends U> g,
899     BiFunction<? super T,? super U,? extends V> a);
900 jsr166 1.46 public abstract <T> CompletableFuture<Void> runAfterEither
901 jsr166 1.38 (CompletableFuture<T> f,
902 jsr166 1.46 CompletionStage<?> g,
903     java.lang.Runnable a);
904 jsr166 1.38 public abstract <T> CompletableFuture<Void> acceptEither
905     (CompletableFuture<T> f,
906     CompletionStage<? extends T> g,
907     Consumer<? super T> a);
908 jsr166 1.46 public abstract <T,U> CompletableFuture<U> applyToEither
909 jsr166 1.38 (CompletableFuture<T> f,
910 jsr166 1.46 CompletionStage<? extends T> g,
911     Function<? super T,U> a);
912 dl 1.198 public abstract <T> CompletableFuture<T> exceptionally
913     (CompletableFuture<T> f,
914     Function<Throwable, ? extends T> fn);
915     public abstract <T> CompletableFuture<T> exceptionallyCompose
916     (CompletableFuture<T> f,
917     Function<Throwable, ? extends CompletionStage<T>> fn);
918 jsr166 1.46 }
919    
920     /**
921     * exceptionally action is not invoked when source completes
922     * normally, and source result is propagated
923     */
924     public void testExceptionally_normalCompletion() {
925 dl 1.198 for (ExecutionMode m : ExecutionMode.values())
926 jsr166 1.46 for (boolean createIncomplete : new boolean[] { true, false })
927     for (Integer v1 : new Integer[] { 1, null })
928     {
929     final CompletableFuture<Integer> f = new CompletableFuture<>();
930 jsr166 1.78 if (!createIncomplete) assertTrue(f.complete(v1));
931 dl 1.198 final CompletableFuture<Integer> g = m.exceptionally
932     (f, (Throwable t) -> {
933 jsr166 1.127 threadFail("should not be called");
934     return null; // unreached
935 jsr166 1.46 });
936 jsr166 1.78 if (createIncomplete) assertTrue(f.complete(v1));
937 jsr166 1.38
938 jsr166 1.46 checkCompletedNormally(g, v1);
939     checkCompletedNormally(f, v1);
940     }}
941 jsr166 1.38
942 jsr166 1.35 /**
943 dl 1.5 * exceptionally action completes with function value on source
944 jsr166 1.46 * exception
945     */
946     public void testExceptionally_exceptionalCompletion() {
947 dl 1.198 for (ExecutionMode m : ExecutionMode.values())
948 jsr166 1.46 for (boolean createIncomplete : new boolean[] { true, false })
949     for (Integer v1 : new Integer[] { 1, null })
950     {
951     final AtomicInteger a = new AtomicInteger(0);
952     final CFException ex = new CFException();
953     final CompletableFuture<Integer> f = new CompletableFuture<>();
954     if (!createIncomplete) f.completeExceptionally(ex);
955 dl 1.198 final CompletableFuture<Integer> g = m.exceptionally
956     (f, (Throwable t) -> {
957     m.checkExecutionMode();
958 jsr166 1.46 threadAssertSame(t, ex);
959     a.getAndIncrement();
960     return v1;
961     });
962     if (createIncomplete) f.completeExceptionally(ex);
963    
964     checkCompletedNormally(g, v1);
965     assertEquals(1, a.get());
966     }}
967    
968 jsr166 1.136 /**
969     * If an "exceptionally action" throws an exception, it completes
970     * exceptionally with that exception
971     */
972 jsr166 1.46 public void testExceptionally_exceptionalCompletionActionFailed() {
973 dl 1.198 for (ExecutionMode m : ExecutionMode.values())
974 jsr166 1.46 for (boolean createIncomplete : new boolean[] { true, false })
975     {
976     final AtomicInteger a = new AtomicInteger(0);
977     final CFException ex1 = new CFException();
978     final CFException ex2 = new CFException();
979     final CompletableFuture<Integer> f = new CompletableFuture<>();
980     if (!createIncomplete) f.completeExceptionally(ex1);
981 dl 1.198 final CompletableFuture<Integer> g = m.exceptionally
982     (f, (Throwable t) -> {
983     m.checkExecutionMode();
984 jsr166 1.46 threadAssertSame(t, ex1);
985     a.getAndIncrement();
986     throw ex2;
987     });
988     if (createIncomplete) f.completeExceptionally(ex1);
989    
990 jsr166 1.72 checkCompletedWithWrappedException(g, ex2);
991 jsr166 1.136 checkCompletedExceptionally(f, ex1);
992 jsr166 1.46 assertEquals(1, a.get());
993     }}
994    
995     /**
996 jsr166 1.75 * whenComplete action executes on normal completion, propagating
997     * source result.
998     */
999 jsr166 1.126 public void testWhenComplete_normalCompletion() {
1000 jsr166 1.75 for (ExecutionMode m : ExecutionMode.values())
1001     for (boolean createIncomplete : new boolean[] { true, false })
1002     for (Integer v1 : new Integer[] { 1, null })
1003     {
1004     final AtomicInteger a = new AtomicInteger(0);
1005     final CompletableFuture<Integer> f = new CompletableFuture<>();
1006 jsr166 1.78 if (!createIncomplete) assertTrue(f.complete(v1));
1007 jsr166 1.75 final CompletableFuture<Integer> g = m.whenComplete
1008     (f,
1009 jsr166 1.135 (Integer result, Throwable t) -> {
1010 jsr166 1.75 m.checkExecutionMode();
1011 jsr166 1.135 threadAssertSame(result, v1);
1012 jsr166 1.75 threadAssertNull(t);
1013     a.getAndIncrement();
1014     });
1015 jsr166 1.78 if (createIncomplete) assertTrue(f.complete(v1));
1016 jsr166 1.75
1017     checkCompletedNormally(g, v1);
1018     checkCompletedNormally(f, v1);
1019     assertEquals(1, a.get());
1020     }}
1021    
1022     /**
1023     * whenComplete action executes on exceptional completion, propagating
1024     * source result.
1025     */
1026     public void testWhenComplete_exceptionalCompletion() {
1027     for (ExecutionMode m : ExecutionMode.values())
1028     for (boolean createIncomplete : new boolean[] { true, false })
1029     {
1030     final AtomicInteger a = new AtomicInteger(0);
1031     final CFException ex = new CFException();
1032     final CompletableFuture<Integer> f = new CompletableFuture<>();
1033     if (!createIncomplete) f.completeExceptionally(ex);
1034     final CompletableFuture<Integer> g = m.whenComplete
1035     (f,
1036 jsr166 1.135 (Integer result, Throwable t) -> {
1037 jsr166 1.75 m.checkExecutionMode();
1038 jsr166 1.135 threadAssertNull(result);
1039 jsr166 1.75 threadAssertSame(t, ex);
1040     a.getAndIncrement();
1041     });
1042     if (createIncomplete) f.completeExceptionally(ex);
1043    
1044     checkCompletedWithWrappedException(g, ex);
1045     checkCompletedExceptionally(f, ex);
1046     assertEquals(1, a.get());
1047     }}
1048    
1049     /**
1050     * whenComplete action executes on cancelled source, propagating
1051     * CancellationException.
1052     */
1053     public void testWhenComplete_sourceCancelled() {
1054     for (ExecutionMode m : ExecutionMode.values())
1055     for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1056     for (boolean createIncomplete : new boolean[] { true, false })
1057     {
1058     final AtomicInteger a = new AtomicInteger(0);
1059     final CompletableFuture<Integer> f = new CompletableFuture<>();
1060     if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1061     final CompletableFuture<Integer> g = m.whenComplete
1062     (f,
1063 jsr166 1.135 (Integer result, Throwable t) -> {
1064 jsr166 1.75 m.checkExecutionMode();
1065 jsr166 1.135 threadAssertNull(result);
1066 jsr166 1.75 threadAssertTrue(t instanceof CancellationException);
1067     a.getAndIncrement();
1068     });
1069     if (createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1070    
1071     checkCompletedWithWrappedCancellationException(g);
1072     checkCancelled(f);
1073     assertEquals(1, a.get());
1074     }}
1075    
1076     /**
1077     * If a whenComplete action throws an exception when triggered by
1078     * a normal completion, it completes exceptionally
1079     */
1080 jsr166 1.132 public void testWhenComplete_sourceCompletedNormallyActionFailed() {
1081 jsr166 1.75 for (boolean createIncomplete : new boolean[] { true, false })
1082     for (ExecutionMode m : ExecutionMode.values())
1083     for (Integer v1 : new Integer[] { 1, null })
1084     {
1085     final AtomicInteger a = new AtomicInteger(0);
1086     final CFException ex = new CFException();
1087     final CompletableFuture<Integer> f = new CompletableFuture<>();
1088 jsr166 1.78 if (!createIncomplete) assertTrue(f.complete(v1));
1089 jsr166 1.75 final CompletableFuture<Integer> g = m.whenComplete
1090     (f,
1091 jsr166 1.135 (Integer result, Throwable t) -> {
1092 jsr166 1.75 m.checkExecutionMode();
1093 jsr166 1.135 threadAssertSame(result, v1);
1094 jsr166 1.75 threadAssertNull(t);
1095     a.getAndIncrement();
1096     throw ex;
1097     });
1098 jsr166 1.78 if (createIncomplete) assertTrue(f.complete(v1));
1099 jsr166 1.75
1100     checkCompletedWithWrappedException(g, ex);
1101     checkCompletedNormally(f, v1);
1102     assertEquals(1, a.get());
1103     }}
1104    
1105     /**
1106     * If a whenComplete action throws an exception when triggered by
1107     * a source completion that also throws an exception, the source
1108 jsr166 1.134 * exception takes precedence (unlike handle)
1109 jsr166 1.75 */
1110 jsr166 1.134 public void testWhenComplete_sourceFailedActionFailed() {
1111 jsr166 1.75 for (boolean createIncomplete : new boolean[] { true, false })
1112     for (ExecutionMode m : ExecutionMode.values())
1113     {
1114     final AtomicInteger a = new AtomicInteger(0);
1115     final CFException ex1 = new CFException();
1116     final CFException ex2 = new CFException();
1117     final CompletableFuture<Integer> f = new CompletableFuture<>();
1118    
1119     if (!createIncomplete) f.completeExceptionally(ex1);
1120     final CompletableFuture<Integer> g = m.whenComplete
1121     (f,
1122 jsr166 1.135 (Integer result, Throwable t) -> {
1123 jsr166 1.75 m.checkExecutionMode();
1124     threadAssertSame(t, ex1);
1125 jsr166 1.135 threadAssertNull(result);
1126 jsr166 1.75 a.getAndIncrement();
1127     throw ex2;
1128     });
1129     if (createIncomplete) f.completeExceptionally(ex1);
1130    
1131     checkCompletedWithWrappedException(g, ex1);
1132     checkCompletedExceptionally(f, ex1);
1133 jsr166 1.139 if (testImplementationDetails) {
1134     assertEquals(1, ex1.getSuppressed().length);
1135     assertSame(ex2, ex1.getSuppressed()[0]);
1136     }
1137 jsr166 1.75 assertEquals(1, a.get());
1138     }}
1139    
1140     /**
1141 jsr166 1.46 * handle action completes normally with function value on normal
1142     * completion of source
1143     */
1144     public void testHandle_normalCompletion() {
1145     for (ExecutionMode m : ExecutionMode.values())
1146     for (boolean createIncomplete : new boolean[] { true, false })
1147     for (Integer v1 : new Integer[] { 1, null })
1148     {
1149     final CompletableFuture<Integer> f = new CompletableFuture<>();
1150     final AtomicInteger a = new AtomicInteger(0);
1151 jsr166 1.78 if (!createIncomplete) assertTrue(f.complete(v1));
1152 jsr166 1.46 final CompletableFuture<Integer> g = m.handle
1153     (f,
1154 jsr166 1.135 (Integer result, Throwable t) -> {
1155 jsr166 1.57 m.checkExecutionMode();
1156 jsr166 1.135 threadAssertSame(result, v1);
1157 jsr166 1.46 threadAssertNull(t);
1158     a.getAndIncrement();
1159     return inc(v1);
1160     });
1161 jsr166 1.78 if (createIncomplete) assertTrue(f.complete(v1));
1162 jsr166 1.46
1163     checkCompletedNormally(g, inc(v1));
1164     checkCompletedNormally(f, v1);
1165     assertEquals(1, a.get());
1166     }}
1167    
1168     /**
1169     * handle action completes normally with function value on
1170     * exceptional completion of source
1171 dl 1.5 */
1172 jsr166 1.46 public void testHandle_exceptionalCompletion() {
1173     for (ExecutionMode m : ExecutionMode.values())
1174     for (boolean createIncomplete : new boolean[] { true, false })
1175     for (Integer v1 : new Integer[] { 1, null })
1176     {
1177     final CompletableFuture<Integer> f = new CompletableFuture<>();
1178     final AtomicInteger a = new AtomicInteger(0);
1179     final CFException ex = new CFException();
1180     if (!createIncomplete) f.completeExceptionally(ex);
1181     final CompletableFuture<Integer> g = m.handle
1182     (f,
1183 jsr166 1.135 (Integer result, Throwable t) -> {
1184 jsr166 1.57 m.checkExecutionMode();
1185 jsr166 1.135 threadAssertNull(result);
1186 jsr166 1.46 threadAssertSame(t, ex);
1187     a.getAndIncrement();
1188     return v1;
1189     });
1190     if (createIncomplete) f.completeExceptionally(ex);
1191 dl 1.5
1192 jsr166 1.46 checkCompletedNormally(g, v1);
1193 jsr166 1.72 checkCompletedExceptionally(f, ex);
1194 jsr166 1.46 assertEquals(1, a.get());
1195     }}
1196 dl 1.5
1197     /**
1198 jsr166 1.46 * handle action completes normally with function value on
1199     * cancelled source
1200 dl 1.5 */
1201 jsr166 1.46 public void testHandle_sourceCancelled() {
1202     for (ExecutionMode m : ExecutionMode.values())
1203     for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1204     for (boolean createIncomplete : new boolean[] { true, false })
1205     for (Integer v1 : new Integer[] { 1, null })
1206     {
1207     final CompletableFuture<Integer> f = new CompletableFuture<>();
1208     final AtomicInteger a = new AtomicInteger(0);
1209     if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1210     final CompletableFuture<Integer> g = m.handle
1211     (f,
1212 jsr166 1.135 (Integer result, Throwable t) -> {
1213 jsr166 1.57 m.checkExecutionMode();
1214 jsr166 1.135 threadAssertNull(result);
1215 jsr166 1.46 threadAssertTrue(t instanceof CancellationException);
1216     a.getAndIncrement();
1217     return v1;
1218     });
1219     if (createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
1220    
1221     checkCompletedNormally(g, v1);
1222     checkCancelled(f);
1223     assertEquals(1, a.get());
1224     }}
1225 jsr166 1.15
1226 jsr166 1.46 /**
1227 jsr166 1.134 * If a "handle action" throws an exception when triggered by
1228     * a normal completion, it completes exceptionally
1229 jsr166 1.46 */
1230 jsr166 1.134 public void testHandle_sourceCompletedNormallyActionFailed() {
1231 jsr166 1.46 for (ExecutionMode m : ExecutionMode.values())
1232     for (boolean createIncomplete : new boolean[] { true, false })
1233 jsr166 1.134 for (Integer v1 : new Integer[] { 1, null })
1234 jsr166 1.46 {
1235     final CompletableFuture<Integer> f = new CompletableFuture<>();
1236     final AtomicInteger a = new AtomicInteger(0);
1237 jsr166 1.134 final CFException ex = new CFException();
1238     if (!createIncomplete) assertTrue(f.complete(v1));
1239 jsr166 1.46 final CompletableFuture<Integer> g = m.handle
1240     (f,
1241 jsr166 1.135 (Integer result, Throwable t) -> {
1242 jsr166 1.57 m.checkExecutionMode();
1243 jsr166 1.135 threadAssertSame(result, v1);
1244 jsr166 1.134 threadAssertNull(t);
1245 jsr166 1.46 a.getAndIncrement();
1246 jsr166 1.134 throw ex;
1247 jsr166 1.46 });
1248 jsr166 1.134 if (createIncomplete) assertTrue(f.complete(v1));
1249 dl 1.5
1250 jsr166 1.134 checkCompletedWithWrappedException(g, ex);
1251     checkCompletedNormally(f, v1);
1252 jsr166 1.46 assertEquals(1, a.get());
1253     }}
1254 jsr166 1.15
1255 jsr166 1.133 /**
1256     * If a "handle action" throws an exception when triggered by
1257 jsr166 1.134 * a source completion that also throws an exception, the action
1258     * exception takes precedence (unlike whenComplete)
1259 jsr166 1.133 */
1260 jsr166 1.134 public void testHandle_sourceFailedActionFailed() {
1261     for (boolean createIncomplete : new boolean[] { true, false })
1262 jsr166 1.46 for (ExecutionMode m : ExecutionMode.values())
1263     {
1264 jsr166 1.134 final AtomicInteger a = new AtomicInteger(0);
1265     final CFException ex1 = new CFException();
1266     final CFException ex2 = new CFException();
1267 jsr166 1.46 final CompletableFuture<Integer> f = new CompletableFuture<>();
1268 jsr166 1.134
1269     if (!createIncomplete) f.completeExceptionally(ex1);
1270 jsr166 1.46 final CompletableFuture<Integer> g = m.handle
1271     (f,
1272 jsr166 1.135 (Integer result, Throwable t) -> {
1273 jsr166 1.57 m.checkExecutionMode();
1274 jsr166 1.135 threadAssertNull(result);
1275 jsr166 1.134 threadAssertSame(ex1, t);
1276 jsr166 1.46 a.getAndIncrement();
1277 jsr166 1.134 throw ex2;
1278 jsr166 1.46 });
1279 jsr166 1.134 if (createIncomplete) f.completeExceptionally(ex1);
1280 jsr166 1.15
1281 jsr166 1.134 checkCompletedWithWrappedException(g, ex2);
1282     checkCompletedExceptionally(f, ex1);
1283 jsr166 1.46 assertEquals(1, a.get());
1284     }}
1285 dl 1.5
1286     /**
1287     * runAsync completes after running Runnable
1288     */
1289 jsr166 1.57 public void testRunAsync_normalCompletion() {
1290     ExecutionMode[] executionModes = {
1291     ExecutionMode.ASYNC,
1292     ExecutionMode.EXECUTOR,
1293     };
1294     for (ExecutionMode m : executionModes)
1295     {
1296     final Noop r = new Noop(m);
1297     final CompletableFuture<Void> f = m.runAsync(r);
1298 dl 1.5 assertNull(f.join());
1299 jsr166 1.14 checkCompletedNormally(f, null);
1300 jsr166 1.62 r.assertInvoked();
1301 jsr166 1.57 }}
1302 dl 1.5
1303     /**
1304     * failing runAsync completes exceptionally after running Runnable
1305     */
1306 jsr166 1.57 public void testRunAsync_exceptionalCompletion() {
1307     ExecutionMode[] executionModes = {
1308     ExecutionMode.ASYNC,
1309     ExecutionMode.EXECUTOR,
1310     };
1311     for (ExecutionMode m : executionModes)
1312     {
1313     final FailingRunnable r = new FailingRunnable(m);
1314     final CompletableFuture<Void> f = m.runAsync(r);
1315 jsr166 1.151 checkCompletedWithWrappedException(f, r.ex);
1316 jsr166 1.62 r.assertInvoked();
1317 jsr166 1.57 }}
1318 dl 1.5
1319 jsr166 1.187 @SuppressWarnings("FutureReturnValueIgnored")
1320 jsr166 1.155 public void testRunAsync_rejectingExecutor() {
1321     CountingRejectingExecutor e = new CountingRejectingExecutor();
1322     try {
1323     CompletableFuture.runAsync(() -> {}, e);
1324     shouldThrow();
1325     } catch (Throwable t) {
1326     assertSame(e.ex, t);
1327     }
1328    
1329     assertEquals(1, e.count.get());
1330     }
1331    
1332 dl 1.5 /**
1333     * supplyAsync completes with result of supplier
1334     */
1335 jsr166 1.58 public void testSupplyAsync_normalCompletion() {
1336     ExecutionMode[] executionModes = {
1337     ExecutionMode.ASYNC,
1338     ExecutionMode.EXECUTOR,
1339     };
1340     for (ExecutionMode m : executionModes)
1341     for (Integer v1 : new Integer[] { 1, null })
1342     {
1343     final IntegerSupplier r = new IntegerSupplier(m, v1);
1344     final CompletableFuture<Integer> f = m.supplyAsync(r);
1345     assertSame(v1, f.join());
1346     checkCompletedNormally(f, v1);
1347 jsr166 1.62 r.assertInvoked();
1348 jsr166 1.58 }}
1349 dl 1.5
1350     /**
1351     * Failing supplyAsync completes exceptionally
1352     */
1353 jsr166 1.58 public void testSupplyAsync_exceptionalCompletion() {
1354     ExecutionMode[] executionModes = {
1355     ExecutionMode.ASYNC,
1356     ExecutionMode.EXECUTOR,
1357     };
1358     for (ExecutionMode m : executionModes)
1359     {
1360     FailingSupplier r = new FailingSupplier(m);
1361     CompletableFuture<Integer> f = m.supplyAsync(r);
1362 jsr166 1.151 checkCompletedWithWrappedException(f, r.ex);
1363 jsr166 1.62 r.assertInvoked();
1364 jsr166 1.58 }}
1365 dl 1.5
1366 jsr166 1.187 @SuppressWarnings("FutureReturnValueIgnored")
1367 jsr166 1.155 public void testSupplyAsync_rejectingExecutor() {
1368     CountingRejectingExecutor e = new CountingRejectingExecutor();
1369     try {
1370     CompletableFuture.supplyAsync(() -> null, e);
1371     shouldThrow();
1372     } catch (Throwable t) {
1373     assertSame(e.ex, t);
1374     }
1375    
1376     assertEquals(1, e.count.get());
1377     }
1378    
1379 jsr166 1.7 // seq completion methods
1380 jsr166 1.6
1381 dl 1.5 /**
1382     * thenRun result completes normally after normal completion of source
1383     */
1384 jsr166 1.48 public void testThenRun_normalCompletion() {
1385     for (ExecutionMode m : ExecutionMode.values())
1386     for (Integer v1 : new Integer[] { 1, null })
1387     {
1388     final CompletableFuture<Integer> f = new CompletableFuture<>();
1389 jsr166 1.90 final Noop[] rs = new Noop[6];
1390     for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1391    
1392     final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1393     final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1394     final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1395     checkIncomplete(h0);
1396     checkIncomplete(h1);
1397     checkIncomplete(h2);
1398     assertTrue(f.complete(v1));
1399     final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1400     final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1401     final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1402 jsr166 1.23
1403 jsr166 1.90 checkCompletedNormally(h0, null);
1404     checkCompletedNormally(h1, null);
1405     checkCompletedNormally(h2, null);
1406     checkCompletedNormally(h3, null);
1407     checkCompletedNormally(h4, null);
1408     checkCompletedNormally(h5, null);
1409 jsr166 1.48 checkCompletedNormally(f, v1);
1410 jsr166 1.90 for (Noop r : rs) r.assertInvoked();
1411 jsr166 1.48 }}
1412 dl 1.5
1413     /**
1414     * thenRun result completes exceptionally after exceptional
1415     * completion of source
1416     */
1417 jsr166 1.48 public void testThenRun_exceptionalCompletion() {
1418     for (ExecutionMode m : ExecutionMode.values())
1419     {
1420     final CFException ex = new CFException();
1421     final CompletableFuture<Integer> f = new CompletableFuture<>();
1422 jsr166 1.90 final Noop[] rs = new Noop[6];
1423     for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1424    
1425     final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1426     final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1427     final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1428     checkIncomplete(h0);
1429     checkIncomplete(h1);
1430     checkIncomplete(h2);
1431     assertTrue(f.completeExceptionally(ex));
1432     final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1433     final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1434     final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1435 jsr166 1.23
1436 jsr166 1.90 checkCompletedWithWrappedException(h0, ex);
1437     checkCompletedWithWrappedException(h1, ex);
1438     checkCompletedWithWrappedException(h2, ex);
1439     checkCompletedWithWrappedException(h3, ex);
1440     checkCompletedWithWrappedException(h4, ex);
1441     checkCompletedWithWrappedException(h5, ex);
1442 jsr166 1.72 checkCompletedExceptionally(f, ex);
1443 jsr166 1.90 for (Noop r : rs) r.assertNotInvoked();
1444 jsr166 1.48 }}
1445    
1446     /**
1447     * thenRun result completes exceptionally if source cancelled
1448     */
1449     public void testThenRun_sourceCancelled() {
1450     for (ExecutionMode m : ExecutionMode.values())
1451     for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1452     {
1453     final CompletableFuture<Integer> f = new CompletableFuture<>();
1454 jsr166 1.90 final Noop[] rs = new Noop[6];
1455     for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
1456    
1457     final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1458     final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1459     final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1460     checkIncomplete(h0);
1461     checkIncomplete(h1);
1462     checkIncomplete(h2);
1463     assertTrue(f.cancel(mayInterruptIfRunning));
1464     final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1465     final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1466     final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1467 jsr166 1.23
1468 jsr166 1.90 checkCompletedWithWrappedCancellationException(h0);
1469     checkCompletedWithWrappedCancellationException(h1);
1470     checkCompletedWithWrappedCancellationException(h2);
1471     checkCompletedWithWrappedCancellationException(h3);
1472     checkCompletedWithWrappedCancellationException(h4);
1473     checkCompletedWithWrappedCancellationException(h5);
1474 jsr166 1.48 checkCancelled(f);
1475 jsr166 1.90 for (Noop r : rs) r.assertNotInvoked();
1476 jsr166 1.48 }}
1477 dl 1.5
1478     /**
1479     * thenRun result completes exceptionally if action does
1480     */
1481 jsr166 1.48 public void testThenRun_actionFailed() {
1482     for (ExecutionMode m : ExecutionMode.values())
1483     for (Integer v1 : new Integer[] { 1, null })
1484     {
1485     final CompletableFuture<Integer> f = new CompletableFuture<>();
1486 jsr166 1.90 final FailingRunnable[] rs = new FailingRunnable[6];
1487     for (int i = 0; i < rs.length; i++) rs[i] = new FailingRunnable(m);
1488    
1489     final CompletableFuture<Void> h0 = m.thenRun(f, rs[0]);
1490     final CompletableFuture<Void> h1 = m.runAfterBoth(f, f, rs[1]);
1491     final CompletableFuture<Void> h2 = m.runAfterEither(f, f, rs[2]);
1492     assertTrue(f.complete(v1));
1493     final CompletableFuture<Void> h3 = m.thenRun(f, rs[3]);
1494     final CompletableFuture<Void> h4 = m.runAfterBoth(f, f, rs[4]);
1495     final CompletableFuture<Void> h5 = m.runAfterEither(f, f, rs[5]);
1496 jsr166 1.23
1497 jsr166 1.151 checkCompletedWithWrappedException(h0, rs[0].ex);
1498     checkCompletedWithWrappedException(h1, rs[1].ex);
1499     checkCompletedWithWrappedException(h2, rs[2].ex);
1500     checkCompletedWithWrappedException(h3, rs[3].ex);
1501     checkCompletedWithWrappedException(h4, rs[4].ex);
1502     checkCompletedWithWrappedException(h5, rs[5].ex);
1503 jsr166 1.48 checkCompletedNormally(f, v1);
1504     }}
1505 dl 1.5
1506     /**
1507     * thenApply result completes normally after normal completion of source
1508     */
1509 jsr166 1.49 public void testThenApply_normalCompletion() {
1510     for (ExecutionMode m : ExecutionMode.values())
1511     for (Integer v1 : new Integer[] { 1, null })
1512     {
1513     final CompletableFuture<Integer> f = new CompletableFuture<>();
1514 jsr166 1.91 final IncFunction[] rs = new IncFunction[4];
1515     for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1516    
1517     final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1518     final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1519     checkIncomplete(h0);
1520     checkIncomplete(h1);
1521     assertTrue(f.complete(v1));
1522     final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1523     final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1524 jsr166 1.49
1525 jsr166 1.91 checkCompletedNormally(h0, inc(v1));
1526     checkCompletedNormally(h1, inc(v1));
1527     checkCompletedNormally(h2, inc(v1));
1528     checkCompletedNormally(h3, inc(v1));
1529 jsr166 1.49 checkCompletedNormally(f, v1);
1530 jsr166 1.91 for (IncFunction r : rs) r.assertValue(inc(v1));
1531 jsr166 1.49 }}
1532 dl 1.5
1533     /**
1534     * thenApply result completes exceptionally after exceptional
1535     * completion of source
1536     */
1537 jsr166 1.49 public void testThenApply_exceptionalCompletion() {
1538     for (ExecutionMode m : ExecutionMode.values())
1539     {
1540     final CFException ex = new CFException();
1541     final CompletableFuture<Integer> f = new CompletableFuture<>();
1542 jsr166 1.91 final IncFunction[] rs = new IncFunction[4];
1543     for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1544    
1545     final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1546     final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1547     assertTrue(f.completeExceptionally(ex));
1548     final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1549     final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1550 jsr166 1.49
1551 jsr166 1.91 checkCompletedWithWrappedException(h0, ex);
1552     checkCompletedWithWrappedException(h1, ex);
1553     checkCompletedWithWrappedException(h2, ex);
1554     checkCompletedWithWrappedException(h3, ex);
1555 jsr166 1.72 checkCompletedExceptionally(f, ex);
1556 jsr166 1.91 for (IncFunction r : rs) r.assertNotInvoked();
1557 jsr166 1.49 }}
1558 dl 1.5
1559     /**
1560 jsr166 1.49 * thenApply result completes exceptionally if source cancelled
1561 dl 1.5 */
1562 jsr166 1.49 public void testThenApply_sourceCancelled() {
1563     for (ExecutionMode m : ExecutionMode.values())
1564     for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1565     {
1566     final CompletableFuture<Integer> f = new CompletableFuture<>();
1567 jsr166 1.91 final IncFunction[] rs = new IncFunction[4];
1568     for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
1569    
1570     final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1571     final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1572     assertTrue(f.cancel(mayInterruptIfRunning));
1573     final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1574     final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1575 jsr166 1.49
1576 jsr166 1.91 checkCompletedWithWrappedCancellationException(h0);
1577     checkCompletedWithWrappedCancellationException(h1);
1578     checkCompletedWithWrappedCancellationException(h2);
1579     checkCompletedWithWrappedCancellationException(h3);
1580 jsr166 1.49 checkCancelled(f);
1581 jsr166 1.91 for (IncFunction r : rs) r.assertNotInvoked();
1582 jsr166 1.49 }}
1583 dl 1.5
1584     /**
1585 jsr166 1.49 * thenApply result completes exceptionally if action does
1586 dl 1.5 */
1587 jsr166 1.49 public void testThenApply_actionFailed() {
1588     for (ExecutionMode m : ExecutionMode.values())
1589     for (Integer v1 : new Integer[] { 1, null })
1590     {
1591     final CompletableFuture<Integer> f = new CompletableFuture<>();
1592 jsr166 1.91 final FailingFunction[] rs = new FailingFunction[4];
1593     for (int i = 0; i < rs.length; i++) rs[i] = new FailingFunction(m);
1594    
1595     final CompletableFuture<Integer> h0 = m.thenApply(f, rs[0]);
1596     final CompletableFuture<Integer> h1 = m.applyToEither(f, f, rs[1]);
1597     assertTrue(f.complete(v1));
1598     final CompletableFuture<Integer> h2 = m.thenApply(f, rs[2]);
1599     final CompletableFuture<Integer> h3 = m.applyToEither(f, f, rs[3]);
1600 jsr166 1.49
1601 jsr166 1.151 checkCompletedWithWrappedException(h0, rs[0].ex);
1602     checkCompletedWithWrappedException(h1, rs[1].ex);
1603     checkCompletedWithWrappedException(h2, rs[2].ex);
1604     checkCompletedWithWrappedException(h3, rs[3].ex);
1605 jsr166 1.49 checkCompletedNormally(f, v1);
1606     }}
1607 dl 1.5
1608     /**
1609     * thenAccept result completes normally after normal completion of source
1610     */
1611 jsr166 1.50 public void testThenAccept_normalCompletion() {
1612     for (ExecutionMode m : ExecutionMode.values())
1613     for (Integer v1 : new Integer[] { 1, null })
1614     {
1615     final CompletableFuture<Integer> f = new CompletableFuture<>();
1616 jsr166 1.92 final NoopConsumer[] rs = new NoopConsumer[4];
1617     for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1618    
1619     final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1620     final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1621     checkIncomplete(h0);
1622     checkIncomplete(h1);
1623     assertTrue(f.complete(v1));
1624     final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1625     final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1626 jsr166 1.50
1627 jsr166 1.92 checkCompletedNormally(h0, null);
1628     checkCompletedNormally(h1, null);
1629     checkCompletedNormally(h2, null);
1630     checkCompletedNormally(h3, null);
1631 jsr166 1.50 checkCompletedNormally(f, v1);
1632 jsr166 1.92 for (NoopConsumer r : rs) r.assertValue(v1);
1633 jsr166 1.50 }}
1634 dl 1.5
1635     /**
1636     * thenAccept result completes exceptionally after exceptional
1637     * completion of source
1638     */
1639 jsr166 1.50 public void testThenAccept_exceptionalCompletion() {
1640     for (ExecutionMode m : ExecutionMode.values())
1641     {
1642     final CFException ex = new CFException();
1643     final CompletableFuture<Integer> f = new CompletableFuture<>();
1644 jsr166 1.92 final NoopConsumer[] rs = new NoopConsumer[4];
1645     for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1646    
1647     final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1648     final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1649     assertTrue(f.completeExceptionally(ex));
1650     final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1651     final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1652 jsr166 1.50
1653 jsr166 1.92 checkCompletedWithWrappedException(h0, ex);
1654     checkCompletedWithWrappedException(h1, ex);
1655     checkCompletedWithWrappedException(h2, ex);
1656     checkCompletedWithWrappedException(h3, ex);
1657 jsr166 1.72 checkCompletedExceptionally(f, ex);
1658 jsr166 1.92 for (NoopConsumer r : rs) r.assertNotInvoked();
1659 jsr166 1.50 }}
1660 dl 1.5
1661     /**
1662 jsr166 1.61 * thenAccept result completes exceptionally if source cancelled
1663 dl 1.5 */
1664 jsr166 1.61 public void testThenAccept_sourceCancelled() {
1665 jsr166 1.50 for (ExecutionMode m : ExecutionMode.values())
1666 jsr166 1.61 for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1667 jsr166 1.50 {
1668     final CompletableFuture<Integer> f = new CompletableFuture<>();
1669 jsr166 1.92 final NoopConsumer[] rs = new NoopConsumer[4];
1670     for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
1671    
1672     final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1673     final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1674     assertTrue(f.cancel(mayInterruptIfRunning));
1675     final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1676     final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1677 jsr166 1.50
1678 jsr166 1.92 checkCompletedWithWrappedCancellationException(h0);
1679     checkCompletedWithWrappedCancellationException(h1);
1680     checkCompletedWithWrappedCancellationException(h2);
1681     checkCompletedWithWrappedCancellationException(h3);
1682 jsr166 1.61 checkCancelled(f);
1683 jsr166 1.92 for (NoopConsumer r : rs) r.assertNotInvoked();
1684 jsr166 1.50 }}
1685 dl 1.5
1686     /**
1687 jsr166 1.61 * thenAccept result completes exceptionally if action does
1688 dl 1.5 */
1689 jsr166 1.61 public void testThenAccept_actionFailed() {
1690 jsr166 1.50 for (ExecutionMode m : ExecutionMode.values())
1691 jsr166 1.61 for (Integer v1 : new Integer[] { 1, null })
1692 jsr166 1.50 {
1693     final CompletableFuture<Integer> f = new CompletableFuture<>();
1694 jsr166 1.92 final FailingConsumer[] rs = new FailingConsumer[4];
1695     for (int i = 0; i < rs.length; i++) rs[i] = new FailingConsumer(m);
1696    
1697     final CompletableFuture<Void> h0 = m.thenAccept(f, rs[0]);
1698     final CompletableFuture<Void> h1 = m.acceptEither(f, f, rs[1]);
1699     assertTrue(f.complete(v1));
1700     final CompletableFuture<Void> h2 = m.thenAccept(f, rs[2]);
1701     final CompletableFuture<Void> h3 = m.acceptEither(f, f, rs[3]);
1702 jsr166 1.50
1703 jsr166 1.151 checkCompletedWithWrappedException(h0, rs[0].ex);
1704     checkCompletedWithWrappedException(h1, rs[1].ex);
1705     checkCompletedWithWrappedException(h2, rs[2].ex);
1706     checkCompletedWithWrappedException(h3, rs[3].ex);
1707 jsr166 1.61 checkCompletedNormally(f, v1);
1708 jsr166 1.50 }}
1709 dl 1.5
1710     /**
1711 jsr166 1.18 * thenCombine result completes normally after normal completion
1712     * of sources
1713 dl 1.5 */
1714 jsr166 1.51 public void testThenCombine_normalCompletion() {
1715     for (ExecutionMode m : ExecutionMode.values())
1716 jsr166 1.43 for (boolean fFirst : new boolean[] { true, false })
1717 jsr166 1.36 for (Integer v1 : new Integer[] { 1, null })
1718 jsr166 1.47 for (Integer v2 : new Integer[] { 2, null })
1719     {
1720 jsr166 1.36 final CompletableFuture<Integer> f = new CompletableFuture<>();
1721     final CompletableFuture<Integer> g = new CompletableFuture<>();
1722 jsr166 1.93 final SubtractFunction[] rs = new SubtractFunction[6];
1723     for (int i = 0; i < rs.length; i++) rs[i] = new SubtractFunction(m);
1724 jsr166 1.79
1725     final CompletableFuture<Integer> fst = fFirst ? f : g;
1726     final CompletableFuture<Integer> snd = !fFirst ? f : g;
1727     final Integer w1 = fFirst ? v1 : v2;
1728     final Integer w2 = !fFirst ? v1 : v2;
1729    
1730 jsr166 1.93 final CompletableFuture<Integer> h0 = m.thenCombine(f, g, rs[0]);
1731     final CompletableFuture<Integer> h1 = m.thenCombine(fst, fst, rs[1]);
1732 jsr166 1.79 assertTrue(fst.complete(w1));
1733 jsr166 1.93 final CompletableFuture<Integer> h2 = m.thenCombine(f, g, rs[2]);
1734     final CompletableFuture<Integer> h3 = m.thenCombine(fst, fst, rs[3]);
1735     checkIncomplete(h0); rs[0].assertNotInvoked();
1736     checkIncomplete(h2); rs[2].assertNotInvoked();
1737     checkCompletedNormally(h1, subtract(w1, w1));
1738     checkCompletedNormally(h3, subtract(w1, w1));
1739     rs[1].assertValue(subtract(w1, w1));
1740     rs[3].assertValue(subtract(w1, w1));
1741 jsr166 1.79 assertTrue(snd.complete(w2));
1742 jsr166 1.93 final CompletableFuture<Integer> h4 = m.thenCombine(f, g, rs[4]);
1743 jsr166 1.79
1744 jsr166 1.93 checkCompletedNormally(h0, subtract(v1, v2));
1745 jsr166 1.79 checkCompletedNormally(h2, subtract(v1, v2));
1746 jsr166 1.93 checkCompletedNormally(h4, subtract(v1, v2));
1747     rs[0].assertValue(subtract(v1, v2));
1748     rs[2].assertValue(subtract(v1, v2));
1749     rs[4].assertValue(subtract(v1, v2));
1750 jsr166 1.94
1751 jsr166 1.36 checkCompletedNormally(f, v1);
1752     checkCompletedNormally(g, v2);
1753 jsr166 1.47 }}
1754 dl 1.5
1755     /**
1756     * thenCombine result completes exceptionally after exceptional
1757     * completion of either source
1758     */
1759 jsr166 1.79 public void testThenCombine_exceptionalCompletion() throws Throwable {
1760 jsr166 1.36 for (ExecutionMode m : ExecutionMode.values())
1761 jsr166 1.52 for (boolean fFirst : new boolean[] { true, false })
1762 jsr166 1.79 for (boolean failFirst : new boolean[] { true, false })
1763 jsr166 1.47 for (Integer v1 : new Integer[] { 1, null })
1764     {
1765 jsr166 1.36 final CompletableFuture<Integer> f = new CompletableFuture<>();
1766     final CompletableFuture<Integer> g = new CompletableFuture<>();
1767     final CFException ex = new CFException();
1768 jsr166 1.79 final SubtractFunction r1 = new SubtractFunction(m);
1769     final SubtractFunction r2 = new SubtractFunction(m);
1770     final SubtractFunction r3 = new SubtractFunction(m);
1771    
1772     final CompletableFuture<Integer> fst = fFirst ? f : g;
1773     final CompletableFuture<Integer> snd = !fFirst ? f : g;
1774     final Callable<Boolean> complete1 = failFirst ?
1775     () -> fst.completeExceptionally(ex) :
1776     () -> fst.complete(v1);
1777     final Callable<Boolean> complete2 = failFirst ?
1778     () -> snd.complete(v1) :
1779     () -> snd.completeExceptionally(ex);
1780    
1781     final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1782     assertTrue(complete1.call());
1783     final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1784     checkIncomplete(h1);
1785     checkIncomplete(h2);
1786     assertTrue(complete2.call());
1787     final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1788 jsr166 1.18
1789 jsr166 1.79 checkCompletedWithWrappedException(h1, ex);
1790     checkCompletedWithWrappedException(h2, ex);
1791     checkCompletedWithWrappedException(h3, ex);
1792     r1.assertNotInvoked();
1793     r2.assertNotInvoked();
1794     r3.assertNotInvoked();
1795     checkCompletedNormally(failFirst ? snd : fst, v1);
1796     checkCompletedExceptionally(failFirst ? fst : snd, ex);
1797 jsr166 1.47 }}
1798 dl 1.5
1799     /**
1800     * thenCombine result completes exceptionally if either source cancelled
1801     */
1802 jsr166 1.79 public void testThenCombine_sourceCancelled() throws Throwable {
1803 jsr166 1.36 for (ExecutionMode m : ExecutionMode.values())
1804     for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1805 jsr166 1.52 for (boolean fFirst : new boolean[] { true, false })
1806 jsr166 1.79 for (boolean failFirst : new boolean[] { true, false })
1807 jsr166 1.47 for (Integer v1 : new Integer[] { 1, null })
1808     {
1809 jsr166 1.36 final CompletableFuture<Integer> f = new CompletableFuture<>();
1810     final CompletableFuture<Integer> g = new CompletableFuture<>();
1811 jsr166 1.79 final SubtractFunction r1 = new SubtractFunction(m);
1812     final SubtractFunction r2 = new SubtractFunction(m);
1813     final SubtractFunction r3 = new SubtractFunction(m);
1814 jsr166 1.18
1815 jsr166 1.79 final CompletableFuture<Integer> fst = fFirst ? f : g;
1816     final CompletableFuture<Integer> snd = !fFirst ? f : g;
1817     final Callable<Boolean> complete1 = failFirst ?
1818     () -> fst.cancel(mayInterruptIfRunning) :
1819     () -> fst.complete(v1);
1820     final Callable<Boolean> complete2 = failFirst ?
1821     () -> snd.complete(v1) :
1822     () -> snd.cancel(mayInterruptIfRunning);
1823    
1824     final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1825     assertTrue(complete1.call());
1826     final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1827     checkIncomplete(h1);
1828     checkIncomplete(h2);
1829     assertTrue(complete2.call());
1830     final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1831 jsr166 1.36
1832 jsr166 1.79 checkCompletedWithWrappedCancellationException(h1);
1833     checkCompletedWithWrappedCancellationException(h2);
1834     checkCompletedWithWrappedCancellationException(h3);
1835     r1.assertNotInvoked();
1836     r2.assertNotInvoked();
1837     r3.assertNotInvoked();
1838     checkCompletedNormally(failFirst ? snd : fst, v1);
1839     checkCancelled(failFirst ? fst : snd);
1840 jsr166 1.47 }}
1841 dl 1.5
1842     /**
1843 jsr166 1.61 * thenCombine result completes exceptionally if action does
1844     */
1845     public void testThenCombine_actionFailed() {
1846     for (ExecutionMode m : ExecutionMode.values())
1847     for (boolean fFirst : new boolean[] { true, false })
1848     for (Integer v1 : new Integer[] { 1, null })
1849     for (Integer v2 : new Integer[] { 2, null })
1850     {
1851     final CompletableFuture<Integer> f = new CompletableFuture<>();
1852     final CompletableFuture<Integer> g = new CompletableFuture<>();
1853 jsr166 1.79 final FailingBiFunction r1 = new FailingBiFunction(m);
1854     final FailingBiFunction r2 = new FailingBiFunction(m);
1855     final FailingBiFunction r3 = new FailingBiFunction(m);
1856    
1857     final CompletableFuture<Integer> fst = fFirst ? f : g;
1858     final CompletableFuture<Integer> snd = !fFirst ? f : g;
1859     final Integer w1 = fFirst ? v1 : v2;
1860     final Integer w2 = !fFirst ? v1 : v2;
1861    
1862     final CompletableFuture<Integer> h1 = m.thenCombine(f, g, r1);
1863     assertTrue(fst.complete(w1));
1864     final CompletableFuture<Integer> h2 = m.thenCombine(f, g, r2);
1865     assertTrue(snd.complete(w2));
1866     final CompletableFuture<Integer> h3 = m.thenCombine(f, g, r3);
1867 jsr166 1.61
1868 jsr166 1.151 checkCompletedWithWrappedException(h1, r1.ex);
1869     checkCompletedWithWrappedException(h2, r2.ex);
1870     checkCompletedWithWrappedException(h3, r3.ex);
1871 jsr166 1.81 r1.assertInvoked();
1872     r2.assertInvoked();
1873     r3.assertInvoked();
1874 jsr166 1.61 checkCompletedNormally(f, v1);
1875     checkCompletedNormally(g, v2);
1876     }}
1877    
1878     /**
1879 dl 1.5 * thenAcceptBoth result completes normally after normal
1880     * completion of sources
1881     */
1882 jsr166 1.53 public void testThenAcceptBoth_normalCompletion() {
1883 jsr166 1.35 for (ExecutionMode m : ExecutionMode.values())
1884 jsr166 1.53 for (boolean fFirst : new boolean[] { true, false })
1885 jsr166 1.35 for (Integer v1 : new Integer[] { 1, null })
1886 jsr166 1.47 for (Integer v2 : new Integer[] { 2, null })
1887     {
1888 jsr166 1.35 final CompletableFuture<Integer> f = new CompletableFuture<>();
1889     final CompletableFuture<Integer> g = new CompletableFuture<>();
1890 jsr166 1.80 final SubtractAction r1 = new SubtractAction(m);
1891     final SubtractAction r2 = new SubtractAction(m);
1892     final SubtractAction r3 = new SubtractAction(m);
1893    
1894     final CompletableFuture<Integer> fst = fFirst ? f : g;
1895     final CompletableFuture<Integer> snd = !fFirst ? f : g;
1896     final Integer w1 = fFirst ? v1 : v2;
1897     final Integer w2 = !fFirst ? v1 : v2;
1898    
1899     final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1900     assertTrue(fst.complete(w1));
1901     final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1902     checkIncomplete(h1);
1903     checkIncomplete(h2);
1904     r1.assertNotInvoked();
1905     r2.assertNotInvoked();
1906     assertTrue(snd.complete(w2));
1907     final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1908 jsr166 1.35
1909 jsr166 1.80 checkCompletedNormally(h1, null);
1910     checkCompletedNormally(h2, null);
1911     checkCompletedNormally(h3, null);
1912     r1.assertValue(subtract(v1, v2));
1913     r2.assertValue(subtract(v1, v2));
1914     r3.assertValue(subtract(v1, v2));
1915 jsr166 1.35 checkCompletedNormally(f, v1);
1916     checkCompletedNormally(g, v2);
1917 jsr166 1.47 }}
1918 dl 1.5
1919     /**
1920     * thenAcceptBoth result completes exceptionally after exceptional
1921     * completion of either source
1922     */
1923 jsr166 1.80 public void testThenAcceptBoth_exceptionalCompletion() throws Throwable {
1924 jsr166 1.35 for (ExecutionMode m : ExecutionMode.values())
1925 jsr166 1.53 for (boolean fFirst : new boolean[] { true, false })
1926 jsr166 1.80 for (boolean failFirst : new boolean[] { true, false })
1927 jsr166 1.47 for (Integer v1 : new Integer[] { 1, null })
1928     {
1929 jsr166 1.35 final CompletableFuture<Integer> f = new CompletableFuture<>();
1930     final CompletableFuture<Integer> g = new CompletableFuture<>();
1931     final CFException ex = new CFException();
1932 jsr166 1.80 final SubtractAction r1 = new SubtractAction(m);
1933     final SubtractAction r2 = new SubtractAction(m);
1934     final SubtractAction r3 = new SubtractAction(m);
1935    
1936     final CompletableFuture<Integer> fst = fFirst ? f : g;
1937     final CompletableFuture<Integer> snd = !fFirst ? f : g;
1938     final Callable<Boolean> complete1 = failFirst ?
1939     () -> fst.completeExceptionally(ex) :
1940     () -> fst.complete(v1);
1941     final Callable<Boolean> complete2 = failFirst ?
1942     () -> snd.complete(v1) :
1943     () -> snd.completeExceptionally(ex);
1944    
1945     final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1946     assertTrue(complete1.call());
1947     final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1948     checkIncomplete(h1);
1949     checkIncomplete(h2);
1950     assertTrue(complete2.call());
1951     final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1952 jsr166 1.35
1953 jsr166 1.80 checkCompletedWithWrappedException(h1, ex);
1954     checkCompletedWithWrappedException(h2, ex);
1955     checkCompletedWithWrappedException(h3, ex);
1956     r1.assertNotInvoked();
1957     r2.assertNotInvoked();
1958     r3.assertNotInvoked();
1959     checkCompletedNormally(failFirst ? snd : fst, v1);
1960     checkCompletedExceptionally(failFirst ? fst : snd, ex);
1961 jsr166 1.47 }}
1962 dl 1.5
1963     /**
1964     * thenAcceptBoth result completes exceptionally if either source cancelled
1965     */
1966 jsr166 1.80 public void testThenAcceptBoth_sourceCancelled() throws Throwable {
1967 jsr166 1.35 for (ExecutionMode m : ExecutionMode.values())
1968     for (boolean mayInterruptIfRunning : new boolean[] { true, false })
1969 jsr166 1.53 for (boolean fFirst : new boolean[] { true, false })
1970 jsr166 1.80 for (boolean failFirst : new boolean[] { true, false })
1971 jsr166 1.47 for (Integer v1 : new Integer[] { 1, null })
1972     {
1973 jsr166 1.35 final CompletableFuture<Integer> f = new CompletableFuture<>();
1974     final CompletableFuture<Integer> g = new CompletableFuture<>();
1975 jsr166 1.80 final SubtractAction r1 = new SubtractAction(m);
1976     final SubtractAction r2 = new SubtractAction(m);
1977     final SubtractAction r3 = new SubtractAction(m);
1978    
1979     final CompletableFuture<Integer> fst = fFirst ? f : g;
1980     final CompletableFuture<Integer> snd = !fFirst ? f : g;
1981     final Callable<Boolean> complete1 = failFirst ?
1982     () -> fst.cancel(mayInterruptIfRunning) :
1983     () -> fst.complete(v1);
1984     final Callable<Boolean> complete2 = failFirst ?
1985     () -> snd.complete(v1) :
1986     () -> snd.cancel(mayInterruptIfRunning);
1987 jsr166 1.35
1988 jsr166 1.80 final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
1989     assertTrue(complete1.call());
1990     final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
1991     checkIncomplete(h1);
1992     checkIncomplete(h2);
1993     assertTrue(complete2.call());
1994     final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
1995 jsr166 1.22
1996 jsr166 1.80 checkCompletedWithWrappedCancellationException(h1);
1997     checkCompletedWithWrappedCancellationException(h2);
1998     checkCompletedWithWrappedCancellationException(h3);
1999     r1.assertNotInvoked();
2000     r2.assertNotInvoked();
2001     r3.assertNotInvoked();
2002     checkCompletedNormally(failFirst ? snd : fst, v1);
2003     checkCancelled(failFirst ? fst : snd);
2004 jsr166 1.47 }}
2005 jsr166 1.34
2006     /**
2007 jsr166 1.61 * thenAcceptBoth result completes exceptionally if action does
2008     */
2009     public void testThenAcceptBoth_actionFailed() {
2010     for (ExecutionMode m : ExecutionMode.values())
2011     for (boolean fFirst : new boolean[] { true, false })
2012     for (Integer v1 : new Integer[] { 1, null })
2013     for (Integer v2 : new Integer[] { 2, null })
2014     {
2015     final CompletableFuture<Integer> f = new CompletableFuture<>();
2016     final CompletableFuture<Integer> g = new CompletableFuture<>();
2017 jsr166 1.80 final FailingBiConsumer r1 = new FailingBiConsumer(m);
2018     final FailingBiConsumer r2 = new FailingBiConsumer(m);
2019     final FailingBiConsumer r3 = new FailingBiConsumer(m);
2020    
2021     final CompletableFuture<Integer> fst = fFirst ? f : g;
2022     final CompletableFuture<Integer> snd = !fFirst ? f : g;
2023     final Integer w1 = fFirst ? v1 : v2;
2024     final Integer w2 = !fFirst ? v1 : v2;
2025    
2026     final CompletableFuture<Void> h1 = m.thenAcceptBoth(f, g, r1);
2027     assertTrue(fst.complete(w1));
2028     final CompletableFuture<Void> h2 = m.thenAcceptBoth(f, g, r2);
2029     assertTrue(snd.complete(w2));
2030     final CompletableFuture<Void> h3 = m.thenAcceptBoth(f, g, r3);
2031 jsr166 1.61
2032 jsr166 1.151 checkCompletedWithWrappedException(h1, r1.ex);
2033     checkCompletedWithWrappedException(h2, r2.ex);
2034     checkCompletedWithWrappedException(h3, r3.ex);
2035 jsr166 1.81 r1.assertInvoked();
2036     r2.assertInvoked();
2037     r3.assertInvoked();
2038 jsr166 1.61 checkCompletedNormally(f, v1);
2039     checkCompletedNormally(g, v2);
2040     }}
2041    
2042     /**
2043 dl 1.5 * runAfterBoth result completes normally after normal
2044     * completion of sources
2045     */
2046 jsr166 1.54 public void testRunAfterBoth_normalCompletion() {
2047 jsr166 1.34 for (ExecutionMode m : ExecutionMode.values())
2048 jsr166 1.54 for (boolean fFirst : new boolean[] { true, false })
2049 jsr166 1.33 for (Integer v1 : new Integer[] { 1, null })
2050 jsr166 1.47 for (Integer v2 : new Integer[] { 2, null })
2051     {
2052 jsr166 1.33 final CompletableFuture<Integer> f = new CompletableFuture<>();
2053     final CompletableFuture<Integer> g = new CompletableFuture<>();
2054 jsr166 1.81 final Noop r1 = new Noop(m);
2055     final Noop r2 = new Noop(m);
2056     final Noop r3 = new Noop(m);
2057    
2058     final CompletableFuture<Integer> fst = fFirst ? f : g;
2059     final CompletableFuture<Integer> snd = !fFirst ? f : g;
2060     final Integer w1 = fFirst ? v1 : v2;
2061     final Integer w2 = !fFirst ? v1 : v2;
2062 jsr166 1.33
2063 jsr166 1.81 final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2064     assertTrue(fst.complete(w1));
2065     final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2066     checkIncomplete(h1);
2067     checkIncomplete(h2);
2068     r1.assertNotInvoked();
2069     r2.assertNotInvoked();
2070     assertTrue(snd.complete(w2));
2071     final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2072 dl 1.5
2073 jsr166 1.81 checkCompletedNormally(h1, null);
2074     checkCompletedNormally(h2, null);
2075     checkCompletedNormally(h3, null);
2076     r1.assertInvoked();
2077     r2.assertInvoked();
2078     r3.assertInvoked();
2079 jsr166 1.33 checkCompletedNormally(f, v1);
2080     checkCompletedNormally(g, v2);
2081 jsr166 1.47 }}
2082 dl 1.5
2083     /**
2084     * runAfterBoth result completes exceptionally after exceptional
2085     * completion of either source
2086     */
2087 jsr166 1.81 public void testRunAfterBoth_exceptionalCompletion() throws Throwable {
2088 jsr166 1.34 for (ExecutionMode m : ExecutionMode.values())
2089 jsr166 1.54 for (boolean fFirst : new boolean[] { true, false })
2090 jsr166 1.81 for (boolean failFirst : new boolean[] { true, false })
2091 jsr166 1.47 for (Integer v1 : new Integer[] { 1, null })
2092     {
2093 jsr166 1.33 final CompletableFuture<Integer> f = new CompletableFuture<>();
2094     final CompletableFuture<Integer> g = new CompletableFuture<>();
2095     final CFException ex = new CFException();
2096 jsr166 1.81 final Noop r1 = new Noop(m);
2097     final Noop r2 = new Noop(m);
2098     final Noop r3 = new Noop(m);
2099 jsr166 1.33
2100 jsr166 1.81 final CompletableFuture<Integer> fst = fFirst ? f : g;
2101     final CompletableFuture<Integer> snd = !fFirst ? f : g;
2102     final Callable<Boolean> complete1 = failFirst ?
2103     () -> fst.completeExceptionally(ex) :
2104     () -> fst.complete(v1);
2105     final Callable<Boolean> complete2 = failFirst ?
2106     () -> snd.complete(v1) :
2107     () -> snd.completeExceptionally(ex);
2108    
2109     final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2110     assertTrue(complete1.call());
2111     final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2112     checkIncomplete(h1);
2113     checkIncomplete(h2);
2114     assertTrue(complete2.call());
2115     final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2116 dl 1.5
2117 jsr166 1.81 checkCompletedWithWrappedException(h1, ex);
2118     checkCompletedWithWrappedException(h2, ex);
2119     checkCompletedWithWrappedException(h3, ex);
2120     r1.assertNotInvoked();
2121     r2.assertNotInvoked();
2122     r3.assertNotInvoked();
2123     checkCompletedNormally(failFirst ? snd : fst, v1);
2124     checkCompletedExceptionally(failFirst ? fst : snd, ex);
2125 jsr166 1.47 }}
2126 dl 1.5
2127 jsr166 1.4 /**
2128 dl 1.5 * runAfterBoth result completes exceptionally if either source cancelled
2129 jsr166 1.4 */
2130 jsr166 1.81 public void testRunAfterBoth_sourceCancelled() throws Throwable {
2131 jsr166 1.34 for (ExecutionMode m : ExecutionMode.values())
2132 jsr166 1.33 for (boolean mayInterruptIfRunning : new boolean[] { true, false })
2133 jsr166 1.54 for (boolean fFirst : new boolean[] { true, false })
2134 jsr166 1.81 for (boolean failFirst : new boolean[] { true, false })
2135 jsr166 1.47 for (Integer v1 : new Integer[] { 1, null })
2136     {
2137 jsr166 1.33 final CompletableFuture<Integer> f = new CompletableFuture<>();
2138     final CompletableFuture<Integer> g = new CompletableFuture<>();
2139 jsr166 1.81 final Noop r1 = new Noop(m);
2140     final Noop r2 = new Noop(m);
2141     final Noop r3 = new Noop(m);
2142 jsr166 1.33
2143 jsr166 1.81 final CompletableFuture<Integer> fst = fFirst ? f : g;
2144     final CompletableFuture<Integer> snd = !fFirst ? f : g;
2145     final Callable<Boolean> complete1 = failFirst ?
2146     () -> fst.cancel(mayInterruptIfRunning) :
2147     () -> fst.complete(v1);
2148     final Callable<Boolean> complete2 = failFirst ?
2149     () -> snd.complete(v1) :
2150     () -> snd.cancel(mayInterruptIfRunning);
2151    
2152     final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2153     assertTrue(complete1.call());
2154     final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2155     checkIncomplete(h1);
2156     checkIncomplete(h2);
2157     assertTrue(complete2.call());
2158     final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2159 jsr166 1.33
2160 jsr166 1.81 checkCompletedWithWrappedCancellationException(h1);
2161     checkCompletedWithWrappedCancellationException(h2);
2162     checkCompletedWithWrappedCancellationException(h3);
2163     r1.assertNotInvoked();
2164     r2.assertNotInvoked();
2165     r3.assertNotInvoked();
2166     checkCompletedNormally(failFirst ? snd : fst, v1);
2167     checkCancelled(failFirst ? fst : snd);
2168 jsr166 1.47 }}
2169 dl 1.5
2170     /**
2171 jsr166 1.61 * runAfterBoth result completes exceptionally if action does
2172     */
2173     public void testRunAfterBoth_actionFailed() {
2174     for (ExecutionMode m : ExecutionMode.values())
2175     for (boolean fFirst : new boolean[] { true, false })
2176     for (Integer v1 : new Integer[] { 1, null })
2177     for (Integer v2 : new Integer[] { 2, null })
2178     {
2179     final CompletableFuture<Integer> f = new CompletableFuture<>();
2180     final CompletableFuture<Integer> g = new CompletableFuture<>();
2181 jsr166 1.62 final FailingRunnable r1 = new FailingRunnable(m);
2182     final FailingRunnable r2 = new FailingRunnable(m);
2183 jsr166 1.81 final FailingRunnable r3 = new FailingRunnable(m);
2184 jsr166 1.61
2185 jsr166 1.81 final CompletableFuture<Integer> fst = fFirst ? f : g;
2186     final CompletableFuture<Integer> snd = !fFirst ? f : g;
2187     final Integer w1 = fFirst ? v1 : v2;
2188     final Integer w2 = !fFirst ? v1 : v2;
2189    
2190     final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
2191     assertTrue(fst.complete(w1));
2192     final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
2193     assertTrue(snd.complete(w2));
2194     final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);
2195 jsr166 1.61
2196 jsr166 1.151 checkCompletedWithWrappedException(h1, r1.ex);
2197     checkCompletedWithWrappedException(h2, r2.ex);
2198     checkCompletedWithWrappedException(h3, r3.ex);
2199 jsr166 1.81 r1.assertInvoked();
2200     r2.assertInvoked();
2201     r3.assertInvoked();
2202 jsr166 1.61 checkCompletedNormally(f, v1);
2203     checkCompletedNormally(g, v2);
2204     }}
2205    
2206     /**
2207 dl 1.5 * applyToEither result completes normally after normal completion
2208     * of either source
2209     */
2210 jsr166 1.54 public void testApplyToEither_normalCompletion() {
2211 jsr166 1.39 for (ExecutionMode m : ExecutionMode.values())
2212     for (Integer v1 : new Integer[] { 1, null })
2213 jsr166 1.47 for (Integer v2 : new Integer[] { 2, null })
2214     {
2215 jsr166 1.39 final CompletableFuture<Integer> f = new CompletableFuture<>();
2216     final CompletableFuture<Integer> g = new CompletableFuture<>();
2217 jsr166 1.62 final IncFunction[] rs = new IncFunction[6];
2218     for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
2219 jsr166 1.54
2220 jsr166 1.62 final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2221     final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2222     checkIncomplete(h0);
2223     checkIncomplete(h1);
2224     rs[0].assertNotInvoked();
2225     rs[1].assertNotInvoked();
2226     f.complete(v1);
2227     checkCompletedNormally(h0, inc(v1));
2228     checkCompletedNormally(h1, inc(v1));
2229     final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2230     final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2231     checkCompletedNormally(h2, inc(v1));
2232     checkCompletedNormally(h3, inc(v1));
2233     g.complete(v2);
2234 jsr166 1.39
2235 jsr166 1.62 // unspecified behavior - both source completions available
2236     final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2237     final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2238     rs[4].assertValue(h4.join());
2239     rs[5].assertValue(h5.join());
2240     assertTrue(Objects.equals(inc(v1), h4.join()) ||
2241     Objects.equals(inc(v2), h4.join()));
2242     assertTrue(Objects.equals(inc(v1), h5.join()) ||
2243     Objects.equals(inc(v2), h5.join()));
2244 jsr166 1.39
2245     checkCompletedNormally(f, v1);
2246     checkCompletedNormally(g, v2);
2247 jsr166 1.62 checkCompletedNormally(h0, inc(v1));
2248     checkCompletedNormally(h1, inc(v1));
2249     checkCompletedNormally(h2, inc(v1));
2250     checkCompletedNormally(h3, inc(v1));
2251     for (int i = 0; i < 4; i++) rs[i].assertValue(inc(v1));
2252 jsr166 1.47 }}
2253 dl 1.5
2254     /**
2255     * applyToEither result completes exceptionally after exceptional
2256     * completion of either source
2257     */
2258 jsr166 1.62 public void testApplyToEither_exceptionalCompletion() {
2259 jsr166 1.39 for (ExecutionMode m : ExecutionMode.values())
2260 jsr166 1.47 for (Integer v1 : new Integer[] { 1, null })
2261     {
2262 jsr166 1.39 final CompletableFuture<Integer> f = new CompletableFuture<>();
2263     final CompletableFuture<Integer> g = new CompletableFuture<>();
2264 jsr166 1.54 final CFException ex = new CFException();
2265 jsr166 1.62 final IncFunction[] rs = new IncFunction[6];
2266     for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
2267    
2268     final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2269     final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2270     checkIncomplete(h0);
2271     checkIncomplete(h1);
2272     rs[0].assertNotInvoked();
2273     rs[1].assertNotInvoked();
2274     f.completeExceptionally(ex);
2275 jsr166 1.72 checkCompletedWithWrappedException(h0, ex);
2276     checkCompletedWithWrappedException(h1, ex);
2277 jsr166 1.62 final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2278     final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2279 jsr166 1.72 checkCompletedWithWrappedException(h2, ex);
2280     checkCompletedWithWrappedException(h3, ex);
2281 jsr166 1.62 g.complete(v1);
2282 jsr166 1.54
2283 jsr166 1.62 // unspecified behavior - both source completions available
2284     final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2285     final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2286     try {
2287     assertEquals(inc(v1), h4.join());
2288 jsr166 1.66 rs[4].assertValue(inc(v1));
2289 jsr166 1.62 } catch (CompletionException ok) {
2290 jsr166 1.72 checkCompletedWithWrappedException(h4, ex);
2291 jsr166 1.62 rs[4].assertNotInvoked();
2292     }
2293     try {
2294     assertEquals(inc(v1), h5.join());
2295 jsr166 1.66 rs[5].assertValue(inc(v1));
2296 jsr166 1.62 } catch (CompletionException ok) {
2297 jsr166 1.72 checkCompletedWithWrappedException(h5, ex);
2298 jsr166 1.62 rs[5].assertNotInvoked();
2299 jsr166 1.54 }
2300 jsr166 1.39
2301 jsr166 1.72 checkCompletedExceptionally(f, ex);
2302 jsr166 1.62 checkCompletedNormally(g, v1);
2303 jsr166 1.72 checkCompletedWithWrappedException(h0, ex);
2304     checkCompletedWithWrappedException(h1, ex);
2305     checkCompletedWithWrappedException(h2, ex);
2306     checkCompletedWithWrappedException(h3, ex);
2307     checkCompletedWithWrappedException(h4, ex);
2308 jsr166 1.62 for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2309 jsr166 1.47 }}
2310 jsr166 1.39
2311 jsr166 1.66 public void testApplyToEither_exceptionalCompletion2() {
2312     for (ExecutionMode m : ExecutionMode.values())
2313     for (boolean fFirst : new boolean[] { true, false })
2314     for (Integer v1 : new Integer[] { 1, null })
2315     {
2316     final CompletableFuture<Integer> f = new CompletableFuture<>();
2317     final CompletableFuture<Integer> g = new CompletableFuture<>();
2318     final CFException ex = new CFException();
2319     final IncFunction[] rs = new IncFunction[6];
2320     for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
2321    
2322     final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2323     final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2324 jsr166 1.78 assertTrue(fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2325     assertTrue(!fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2326 jsr166 1.66 final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2327     final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2328    
2329     // unspecified behavior - both source completions available
2330     try {
2331     assertEquals(inc(v1), h0.join());
2332     rs[0].assertValue(inc(v1));
2333     } catch (CompletionException ok) {
2334 jsr166 1.72 checkCompletedWithWrappedException(h0, ex);
2335 jsr166 1.66 rs[0].assertNotInvoked();
2336     }
2337     try {
2338     assertEquals(inc(v1), h1.join());
2339     rs[1].assertValue(inc(v1));
2340     } catch (CompletionException ok) {
2341 jsr166 1.72 checkCompletedWithWrappedException(h1, ex);
2342 jsr166 1.66 rs[1].assertNotInvoked();
2343     }
2344     try {
2345     assertEquals(inc(v1), h2.join());
2346     rs[2].assertValue(inc(v1));
2347     } catch (CompletionException ok) {
2348 jsr166 1.72 checkCompletedWithWrappedException(h2, ex);
2349 jsr166 1.66 rs[2].assertNotInvoked();
2350     }
2351     try {
2352     assertEquals(inc(v1), h3.join());
2353     rs[3].assertValue(inc(v1));
2354     } catch (CompletionException ok) {
2355 jsr166 1.72 checkCompletedWithWrappedException(h3, ex);
2356 jsr166 1.66 rs[3].assertNotInvoked();
2357     }
2358    
2359     checkCompletedNormally(f, v1);
2360 jsr166 1.72 checkCompletedExceptionally(g, ex);
2361 jsr166 1.66 }}
2362    
2363 jsr166 1.62 /**
2364     * applyToEither result completes exceptionally if either source cancelled
2365     */
2366     public void testApplyToEither_sourceCancelled() {
2367 jsr166 1.39 for (ExecutionMode m : ExecutionMode.values())
2368 jsr166 1.62 for (boolean mayInterruptIfRunning : new boolean[] { true, false })
2369 jsr166 1.47 for (Integer v1 : new Integer[] { 1, null })
2370     {
2371 jsr166 1.39 final CompletableFuture<Integer> f = new CompletableFuture<>();
2372     final CompletableFuture<Integer> g = new CompletableFuture<>();
2373 jsr166 1.62 final IncFunction[] rs = new IncFunction[6];
2374     for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
2375    
2376     final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2377     final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2378     checkIncomplete(h0);
2379     checkIncomplete(h1);
2380     rs[0].assertNotInvoked();
2381     rs[1].assertNotInvoked();
2382     f.cancel(mayInterruptIfRunning);
2383     checkCompletedWithWrappedCancellationException(h0);
2384     checkCompletedWithWrappedCancellationException(h1);
2385     final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2386     final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2387     checkCompletedWithWrappedCancellationException(h2);
2388     checkCompletedWithWrappedCancellationException(h3);
2389     g.complete(v1);
2390 jsr166 1.39
2391 jsr166 1.62 // unspecified behavior - both source completions available
2392     final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2393     final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2394 jsr166 1.39 try {
2395 jsr166 1.62 assertEquals(inc(v1), h4.join());
2396 jsr166 1.66 rs[4].assertValue(inc(v1));
2397 jsr166 1.39 } catch (CompletionException ok) {
2398 jsr166 1.62 checkCompletedWithWrappedCancellationException(h4);
2399     rs[4].assertNotInvoked();
2400 jsr166 1.39 }
2401     try {
2402 jsr166 1.62 assertEquals(inc(v1), h5.join());
2403 jsr166 1.66 rs[5].assertValue(inc(v1));
2404 jsr166 1.39 } catch (CompletionException ok) {
2405 jsr166 1.62 checkCompletedWithWrappedCancellationException(h5);
2406     rs[5].assertNotInvoked();
2407 jsr166 1.39 }
2408 dl 1.5
2409 jsr166 1.62 checkCancelled(f);
2410     checkCompletedNormally(g, v1);
2411     checkCompletedWithWrappedCancellationException(h0);
2412     checkCompletedWithWrappedCancellationException(h1);
2413     checkCompletedWithWrappedCancellationException(h2);
2414     checkCompletedWithWrappedCancellationException(h3);
2415     for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2416 jsr166 1.47 }}
2417 dl 1.5
2418 jsr166 1.67 public void testApplyToEither_sourceCancelled2() {
2419     for (ExecutionMode m : ExecutionMode.values())
2420     for (boolean mayInterruptIfRunning : new boolean[] { true, false })
2421     for (boolean fFirst : new boolean[] { true, false })
2422     for (Integer v1 : new Integer[] { 1, null })
2423     {
2424     final CompletableFuture<Integer> f = new CompletableFuture<>();
2425     final CompletableFuture<Integer> g = new CompletableFuture<>();
2426     final IncFunction[] rs = new IncFunction[6];
2427     for (int i = 0; i < rs.length; i++) rs[i] = new IncFunction(m);
2428    
2429     final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2430     final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2431 jsr166 1.78 assertTrue(fFirst ? f.complete(v1) : g.cancel(mayInterruptIfRunning));
2432     assertTrue(!fFirst ? f.complete(v1) : g.cancel(mayInterruptIfRunning));
2433 jsr166 1.67 final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2434     final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2435    
2436     // unspecified behavior - both source completions available
2437     try {
2438     assertEquals(inc(v1), h0.join());
2439     rs[0].assertValue(inc(v1));
2440     } catch (CompletionException ok) {
2441     checkCompletedWithWrappedCancellationException(h0);
2442     rs[0].assertNotInvoked();
2443     }
2444     try {
2445     assertEquals(inc(v1), h1.join());
2446     rs[1].assertValue(inc(v1));
2447     } catch (CompletionException ok) {
2448     checkCompletedWithWrappedCancellationException(h1);
2449     rs[1].assertNotInvoked();
2450     }
2451     try {
2452     assertEquals(inc(v1), h2.join());
2453     rs[2].assertValue(inc(v1));
2454     } catch (CompletionException ok) {
2455     checkCompletedWithWrappedCancellationException(h2);
2456     rs[2].assertNotInvoked();
2457     }
2458     try {
2459     assertEquals(inc(v1), h3.join());
2460     rs[3].assertValue(inc(v1));
2461     } catch (CompletionException ok) {
2462     checkCompletedWithWrappedCancellationException(h3);
2463     rs[3].assertNotInvoked();
2464     }
2465    
2466     checkCompletedNormally(f, v1);
2467     checkCancelled(g);
2468     }}
2469    
2470 dl 1.5 /**
2471     * applyToEither result completes exceptionally if action does
2472     */
2473 jsr166 1.62 public void testApplyToEither_actionFailed() {
2474 jsr166 1.39 for (ExecutionMode m : ExecutionMode.values())
2475     for (Integer v1 : new Integer[] { 1, null })
2476 jsr166 1.47 for (Integer v2 : new Integer[] { 2, null })
2477     {
2478 jsr166 1.39 final CompletableFuture<Integer> f = new CompletableFuture<>();
2479     final CompletableFuture<Integer> g = new CompletableFuture<>();
2480 jsr166 1.62 final FailingFunction[] rs = new FailingFunction[6];
2481     for (int i = 0; i < rs.length; i++) rs[i] = new FailingFunction(m);
2482 jsr166 1.39
2483 jsr166 1.62 final CompletableFuture<Integer> h0 = m.applyToEither(f, g, rs[0]);
2484     final CompletableFuture<Integer> h1 = m.applyToEither(g, f, rs[1]);
2485 jsr166 1.39 f.complete(v1);
2486 jsr166 1.62 final CompletableFuture<Integer> h2 = m.applyToEither(f, g, rs[2]);
2487     final CompletableFuture<Integer> h3 = m.applyToEither(g, f, rs[3]);
2488 jsr166 1.151 checkCompletedWithWrappedException(h0, rs[0].ex);
2489     checkCompletedWithWrappedException(h1, rs[1].ex);
2490     checkCompletedWithWrappedException(h2, rs[2].ex);
2491     checkCompletedWithWrappedException(h3, rs[3].ex);
2492 jsr166 1.63 for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2493    
2494     g.complete(v2);
2495    
2496     // unspecified behavior - both source completions available
2497     final CompletableFuture<Integer> h4 = m.applyToEither(f, g, rs[4]);
2498     final CompletableFuture<Integer> h5 = m.applyToEither(g, f, rs[5]);
2499    
2500 jsr166 1.151 checkCompletedWithWrappedException(h4, rs[4].ex);
2501 jsr166 1.63 assertTrue(Objects.equals(v1, rs[4].value) ||
2502     Objects.equals(v2, rs[4].value));
2503 jsr166 1.151 checkCompletedWithWrappedException(h5, rs[5].ex);
2504 jsr166 1.63 assertTrue(Objects.equals(v1, rs[5].value) ||
2505     Objects.equals(v2, rs[5].value));
2506    
2507     checkCompletedNormally(f, v1);
2508     checkCompletedNormally(g, v2);
2509 jsr166 1.47 }}
2510 dl 1.5
2511     /**
2512     * acceptEither result completes normally after normal completion
2513     * of either source
2514     */
2515 jsr166 1.63 public void testAcceptEither_normalCompletion() {
2516 jsr166 1.40 for (ExecutionMode m : ExecutionMode.values())
2517     for (Integer v1 : new Integer[] { 1, null })
2518 jsr166 1.47 for (Integer v2 : new Integer[] { 2, null })
2519     {
2520 jsr166 1.40 final CompletableFuture<Integer> f = new CompletableFuture<>();
2521     final CompletableFuture<Integer> g = new CompletableFuture<>();
2522 jsr166 1.64 final NoopConsumer[] rs = new NoopConsumer[6];
2523     for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
2524 jsr166 1.40
2525 jsr166 1.63 final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
2526     final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
2527     checkIncomplete(h0);
2528     checkIncomplete(h1);
2529     rs[0].assertNotInvoked();
2530     rs[1].assertNotInvoked();
2531 jsr166 1.40 f.complete(v1);
2532 jsr166 1.63 checkCompletedNormally(h0, null);
2533     checkCompletedNormally(h1, null);
2534 jsr166 1.64 rs[0].assertValue(v1);
2535     rs[1].assertValue(v1);
2536 jsr166 1.63 final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2537     final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2538     checkCompletedNormally(h2, null);
2539     checkCompletedNormally(h3, null);
2540 jsr166 1.64 rs[2].assertValue(v1);
2541     rs[3].assertValue(v1);
2542 jsr166 1.40 g.complete(v2);
2543    
2544 jsr166 1.63 // unspecified behavior - both source completions available
2545     final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2546     final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2547     checkCompletedNormally(h4, null);
2548     checkCompletedNormally(h5, null);
2549 jsr166 1.64 assertTrue(Objects.equals(v1, rs[4].value) ||
2550     Objects.equals(v2, rs[4].value));
2551     assertTrue(Objects.equals(v1, rs[5].value) ||
2552     Objects.equals(v2, rs[5].value));
2553 jsr166 1.40
2554     checkCompletedNormally(f, v1);
2555     checkCompletedNormally(g, v2);
2556 jsr166 1.63 checkCompletedNormally(h0, null);
2557     checkCompletedNormally(h1, null);
2558     checkCompletedNormally(h2, null);
2559     checkCompletedNormally(h3, null);
2560 jsr166 1.64 for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2561 jsr166 1.47 }}
2562 dl 1.5
2563     /**
2564     * acceptEither result completes exceptionally after exceptional
2565     * completion of either source
2566     */
2567 jsr166 1.63 public void testAcceptEither_exceptionalCompletion() {
2568 jsr166 1.40 for (ExecutionMode m : ExecutionMode.values())
2569 jsr166 1.47 for (Integer v1 : new Integer[] { 1, null })
2570     {
2571 jsr166 1.40 final CompletableFuture<Integer> f = new CompletableFuture<>();
2572     final CompletableFuture<Integer> g = new CompletableFuture<>();
2573     final CFException ex = new CFException();
2574 jsr166 1.64 final NoopConsumer[] rs = new NoopConsumer[6];
2575     for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
2576 jsr166 1.40
2577 jsr166 1.63 final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
2578     final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
2579     checkIncomplete(h0);
2580     checkIncomplete(h1);
2581     rs[0].assertNotInvoked();
2582     rs[1].assertNotInvoked();
2583 jsr166 1.40 f.completeExceptionally(ex);
2584 jsr166 1.72 checkCompletedWithWrappedException(h0, ex);
2585     checkCompletedWithWrappedException(h1, ex);
2586 jsr166 1.63 final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2587     final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2588 jsr166 1.72 checkCompletedWithWrappedException(h2, ex);
2589     checkCompletedWithWrappedException(h3, ex);
2590 jsr166 1.63
2591 jsr166 1.40 g.complete(v1);
2592    
2593 jsr166 1.63 // unspecified behavior - both source completions available
2594     final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2595     final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2596 jsr166 1.40 try {
2597 jsr166 1.63 assertNull(h4.join());
2598 jsr166 1.64 rs[4].assertValue(v1);
2599 jsr166 1.40 } catch (CompletionException ok) {
2600 jsr166 1.72 checkCompletedWithWrappedException(h4, ex);
2601 jsr166 1.63 rs[4].assertNotInvoked();
2602 jsr166 1.40 }
2603     try {
2604 jsr166 1.63 assertNull(h5.join());
2605 jsr166 1.64 rs[5].assertValue(v1);
2606 jsr166 1.40 } catch (CompletionException ok) {
2607 jsr166 1.72 checkCompletedWithWrappedException(h5, ex);
2608 jsr166 1.63 rs[5].assertNotInvoked();
2609 jsr166 1.40 }
2610 dl 1.5
2611 jsr166 1.72 checkCompletedExceptionally(f, ex);
2612 jsr166 1.40 checkCompletedNormally(g, v1);
2613 jsr166 1.72 checkCompletedWithWrappedException(h0, ex);
2614     checkCompletedWithWrappedException(h1, ex);
2615     checkCompletedWithWrappedException(h2, ex);
2616     checkCompletedWithWrappedException(h3, ex);
2617     checkCompletedWithWrappedException(h4, ex);
2618 jsr166 1.63 for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2619 jsr166 1.47 }}
2620 dl 1.5
2621 jsr166 1.68 public void testAcceptEither_exceptionalCompletion2() {
2622     for (ExecutionMode m : ExecutionMode.values())
2623     for (boolean fFirst : new boolean[] { true, false })
2624     for (Integer v1 : new Integer[] { 1, null })
2625     {
2626     final CompletableFuture<Integer> f = new CompletableFuture<>();
2627     final CompletableFuture<Integer> g = new CompletableFuture<>();
2628     final CFException ex = new CFException();
2629     final NoopConsumer[] rs = new NoopConsumer[6];
2630     for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
2631    
2632     final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
2633     final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
2634 jsr166 1.78 assertTrue(fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2635     assertTrue(!fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2636 jsr166 1.68 final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2637     final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2638    
2639     // unspecified behavior - both source completions available
2640     try {
2641 jsr166 1.184 assertNull(h0.join());
2642 jsr166 1.68 rs[0].assertValue(v1);
2643     } catch (CompletionException ok) {
2644 jsr166 1.72 checkCompletedWithWrappedException(h0, ex);
2645 jsr166 1.68 rs[0].assertNotInvoked();
2646     }
2647     try {
2648 jsr166 1.184 assertNull(h1.join());
2649 jsr166 1.68 rs[1].assertValue(v1);
2650     } catch (CompletionException ok) {
2651 jsr166 1.72 checkCompletedWithWrappedException(h1, ex);
2652 jsr166 1.68 rs[1].assertNotInvoked();
2653     }
2654     try {
2655 jsr166 1.184 assertNull(h2.join());
2656 jsr166 1.68 rs[2].assertValue(v1);
2657     } catch (CompletionException ok) {
2658 jsr166 1.72 checkCompletedWithWrappedException(h2, ex);
2659 jsr166 1.68 rs[2].assertNotInvoked();
2660     }
2661     try {
2662 jsr166 1.184 assertNull(h3.join());
2663 jsr166 1.68 rs[3].assertValue(v1);
2664     } catch (CompletionException ok) {
2665 jsr166 1.72 checkCompletedWithWrappedException(h3, ex);
2666 jsr166 1.68 rs[3].assertNotInvoked();
2667     }
2668    
2669     checkCompletedNormally(f, v1);
2670 jsr166 1.72 checkCompletedExceptionally(g, ex);
2671 jsr166 1.68 }}
2672    
2673 dl 1.5 /**
2674     * acceptEither result completes exceptionally if either source cancelled
2675     */
2676 jsr166 1.63 public void testAcceptEither_sourceCancelled() {
2677 jsr166 1.40 for (ExecutionMode m : ExecutionMode.values())
2678     for (boolean mayInterruptIfRunning : new boolean[] { true, false })
2679 jsr166 1.47 for (Integer v1 : new Integer[] { 1, null })
2680     {
2681 jsr166 1.40 final CompletableFuture<Integer> f = new CompletableFuture<>();
2682     final CompletableFuture<Integer> g = new CompletableFuture<>();
2683 jsr166 1.64 final NoopConsumer[] rs = new NoopConsumer[6];
2684     for (int i = 0; i < rs.length; i++) rs[i] = new NoopConsumer(m);
2685 jsr166 1.63
2686     final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
2687     final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
2688     checkIncomplete(h0);
2689     checkIncomplete(h1);
2690     rs[0].assertNotInvoked();
2691     rs[1].assertNotInvoked();
2692     f.cancel(mayInterruptIfRunning);
2693     checkCompletedWithWrappedCancellationException(h0);
2694     checkCompletedWithWrappedCancellationException(h1);
2695     final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2696     final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2697     checkCompletedWithWrappedCancellationException(h2);
2698     checkCompletedWithWrappedCancellationException(h3);
2699 jsr166 1.40
2700     g.complete(v1);
2701    
2702 jsr166 1.63 // unspecified behavior - both source completions available
2703     final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2704     final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2705     try {
2706     assertNull(h4.join());
2707 jsr166 1.64 rs[4].assertValue(v1);
2708 jsr166 1.63 } catch (CompletionException ok) {
2709     checkCompletedWithWrappedCancellationException(h4);
2710     rs[4].assertNotInvoked();
2711     }
2712     try {
2713     assertNull(h5.join());
2714 jsr166 1.64 rs[5].assertValue(v1);
2715 jsr166 1.63 } catch (CompletionException ok) {
2716     checkCompletedWithWrappedCancellationException(h5);
2717     rs[5].assertNotInvoked();
2718     }
2719    
2720 jsr166 1.40 checkCancelled(f);
2721     checkCompletedNormally(g, v1);
2722 jsr166 1.63 checkCompletedWithWrappedCancellationException(h0);
2723     checkCompletedWithWrappedCancellationException(h1);
2724     checkCompletedWithWrappedCancellationException(h2);
2725     checkCompletedWithWrappedCancellationException(h3);
2726     for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2727 jsr166 1.47 }}
2728 jsr166 1.40
2729 jsr166 1.63 /**
2730     * acceptEither result completes exceptionally if action does
2731     */
2732     public void testAcceptEither_actionFailed() {
2733 jsr166 1.40 for (ExecutionMode m : ExecutionMode.values())
2734 jsr166 1.47 for (Integer v1 : new Integer[] { 1, null })
2735 jsr166 1.63 for (Integer v2 : new Integer[] { 2, null })
2736 jsr166 1.47 {
2737 jsr166 1.40 final CompletableFuture<Integer> f = new CompletableFuture<>();
2738     final CompletableFuture<Integer> g = new CompletableFuture<>();
2739 jsr166 1.63 final FailingConsumer[] rs = new FailingConsumer[6];
2740     for (int i = 0; i < rs.length; i++) rs[i] = new FailingConsumer(m);
2741 jsr166 1.40
2742 jsr166 1.63 final CompletableFuture<Void> h0 = m.acceptEither(f, g, rs[0]);
2743     final CompletableFuture<Void> h1 = m.acceptEither(g, f, rs[1]);
2744 jsr166 1.40 f.complete(v1);
2745 jsr166 1.63 final CompletableFuture<Void> h2 = m.acceptEither(f, g, rs[2]);
2746     final CompletableFuture<Void> h3 = m.acceptEither(g, f, rs[3]);
2747 jsr166 1.151 checkCompletedWithWrappedException(h0, rs[0].ex);
2748     checkCompletedWithWrappedException(h1, rs[1].ex);
2749     checkCompletedWithWrappedException(h2, rs[2].ex);
2750     checkCompletedWithWrappedException(h3, rs[3].ex);
2751 jsr166 1.63 for (int i = 0; i < 4; i++) rs[i].assertValue(v1);
2752 jsr166 1.40
2753 jsr166 1.63 g.complete(v2);
2754 jsr166 1.40
2755 jsr166 1.63 // unspecified behavior - both source completions available
2756     final CompletableFuture<Void> h4 = m.acceptEither(f, g, rs[4]);
2757     final CompletableFuture<Void> h5 = m.acceptEither(g, f, rs[5]);
2758 jsr166 1.40
2759 jsr166 1.151 checkCompletedWithWrappedException(h4, rs[4].ex);
2760 jsr166 1.63 assertTrue(Objects.equals(v1, rs[4].value) ||
2761     Objects.equals(v2, rs[4].value));
2762 jsr166 1.151 checkCompletedWithWrappedException(h5, rs[5].ex);
2763 jsr166 1.63 assertTrue(Objects.equals(v1, rs[5].value) ||
2764     Objects.equals(v2, rs[5].value));
2765 jsr166 1.40
2766     checkCompletedNormally(f, v1);
2767 jsr166 1.63 checkCompletedNormally(g, v2);
2768 jsr166 1.47 }}
2769 dl 1.5
2770     /**
2771     * runAfterEither result completes normally after normal completion
2772     * of either source
2773     */
2774 jsr166 1.65 public void testRunAfterEither_normalCompletion() {
2775 jsr166 1.41 for (ExecutionMode m : ExecutionMode.values())
2776     for (Integer v1 : new Integer[] { 1, null })
2777 jsr166 1.47 for (Integer v2 : new Integer[] { 2, null })
2778 jsr166 1.162 for (boolean pushNop : new boolean[] { true, false })
2779 jsr166 1.47 {
2780 jsr166 1.41 final CompletableFuture<Integer> f = new CompletableFuture<>();
2781     final CompletableFuture<Integer> g = new CompletableFuture<>();
2782 jsr166 1.65 final Noop[] rs = new Noop[6];
2783     for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
2784 jsr166 1.41
2785 jsr166 1.65 final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2786     final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2787     checkIncomplete(h0);
2788     checkIncomplete(h1);
2789     rs[0].assertNotInvoked();
2790     rs[1].assertNotInvoked();
2791 jsr166 1.162 if (pushNop) { // ad hoc test of intra-completion interference
2792     m.thenRun(f, () -> {});
2793     m.thenRun(g, () -> {});
2794     }
2795 jsr166 1.41 f.complete(v1);
2796 jsr166 1.65 checkCompletedNormally(h0, null);
2797     checkCompletedNormally(h1, null);
2798     rs[0].assertInvoked();
2799     rs[1].assertInvoked();
2800     final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2801     final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2802     checkCompletedNormally(h2, null);
2803     checkCompletedNormally(h3, null);
2804     rs[2].assertInvoked();
2805     rs[3].assertInvoked();
2806 jsr166 1.41
2807     g.complete(v2);
2808    
2809 jsr166 1.65 final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2810     final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2811 jsr166 1.47
2812 jsr166 1.41 checkCompletedNormally(f, v1);
2813     checkCompletedNormally(g, v2);
2814 jsr166 1.65 checkCompletedNormally(h0, null);
2815     checkCompletedNormally(h1, null);
2816     checkCompletedNormally(h2, null);
2817     checkCompletedNormally(h3, null);
2818     checkCompletedNormally(h4, null);
2819     checkCompletedNormally(h5, null);
2820     for (int i = 0; i < 6; i++) rs[i].assertInvoked();
2821 jsr166 1.47 }}
2822 dl 1.5
2823     /**
2824     * runAfterEither result completes exceptionally after exceptional
2825     * completion of either source
2826     */
2827 jsr166 1.65 public void testRunAfterEither_exceptionalCompletion() {
2828 jsr166 1.41 for (ExecutionMode m : ExecutionMode.values())
2829 jsr166 1.47 for (Integer v1 : new Integer[] { 1, null })
2830     {
2831 jsr166 1.41 final CompletableFuture<Integer> f = new CompletableFuture<>();
2832     final CompletableFuture<Integer> g = new CompletableFuture<>();
2833     final CFException ex = new CFException();
2834 jsr166 1.65 final Noop[] rs = new Noop[6];
2835     for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
2836 jsr166 1.41
2837 jsr166 1.65 final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2838     final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2839     checkIncomplete(h0);
2840     checkIncomplete(h1);
2841     rs[0].assertNotInvoked();
2842     rs[1].assertNotInvoked();
2843 jsr166 1.78 assertTrue(f.completeExceptionally(ex));
2844 jsr166 1.72 checkCompletedWithWrappedException(h0, ex);
2845     checkCompletedWithWrappedException(h1, ex);
2846 jsr166 1.65 final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2847     final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2848 jsr166 1.72 checkCompletedWithWrappedException(h2, ex);
2849     checkCompletedWithWrappedException(h3, ex);
2850 jsr166 1.65
2851 jsr166 1.78 assertTrue(g.complete(v1));
2852 jsr166 1.41
2853 jsr166 1.65 // unspecified behavior - both source completions available
2854     final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2855     final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2856     try {
2857     assertNull(h4.join());
2858     rs[4].assertInvoked();
2859     } catch (CompletionException ok) {
2860 jsr166 1.72 checkCompletedWithWrappedException(h4, ex);
2861 jsr166 1.65 rs[4].assertNotInvoked();
2862     }
2863     try {
2864     assertNull(h5.join());
2865     rs[5].assertInvoked();
2866     } catch (CompletionException ok) {
2867 jsr166 1.72 checkCompletedWithWrappedException(h5, ex);
2868 jsr166 1.65 rs[5].assertNotInvoked();
2869     }
2870    
2871 jsr166 1.72 checkCompletedExceptionally(f, ex);
2872 jsr166 1.41 checkCompletedNormally(g, v1);
2873 jsr166 1.72 checkCompletedWithWrappedException(h0, ex);
2874     checkCompletedWithWrappedException(h1, ex);
2875     checkCompletedWithWrappedException(h2, ex);
2876     checkCompletedWithWrappedException(h3, ex);
2877     checkCompletedWithWrappedException(h4, ex);
2878 jsr166 1.65 for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2879 jsr166 1.47 }}
2880 jsr166 1.41
2881 jsr166 1.69 public void testRunAfterEither_exceptionalCompletion2() {
2882     for (ExecutionMode m : ExecutionMode.values())
2883     for (boolean fFirst : new boolean[] { true, false })
2884     for (Integer v1 : new Integer[] { 1, null })
2885     {
2886     final CompletableFuture<Integer> f = new CompletableFuture<>();
2887     final CompletableFuture<Integer> g = new CompletableFuture<>();
2888     final CFException ex = new CFException();
2889     final Noop[] rs = new Noop[6];
2890     for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
2891    
2892     final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2893     final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2894 jsr166 1.78 assertTrue( fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2895     assertTrue(!fFirst ? f.complete(v1) : g.completeExceptionally(ex));
2896 jsr166 1.69 final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2897     final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2898    
2899     // unspecified behavior - both source completions available
2900     try {
2901 jsr166 1.184 assertNull(h0.join());
2902 jsr166 1.69 rs[0].assertInvoked();
2903     } catch (CompletionException ok) {
2904 jsr166 1.72 checkCompletedWithWrappedException(h0, ex);
2905 jsr166 1.69 rs[0].assertNotInvoked();
2906     }
2907     try {
2908 jsr166 1.184 assertNull(h1.join());
2909 jsr166 1.69 rs[1].assertInvoked();
2910     } catch (CompletionException ok) {
2911 jsr166 1.72 checkCompletedWithWrappedException(h1, ex);
2912 jsr166 1.69 rs[1].assertNotInvoked();
2913     }
2914     try {
2915 jsr166 1.184 assertNull(h2.join());
2916 jsr166 1.69 rs[2].assertInvoked();
2917     } catch (CompletionException ok) {
2918 jsr166 1.72 checkCompletedWithWrappedException(h2, ex);
2919 jsr166 1.69 rs[2].assertNotInvoked();
2920     }
2921     try {
2922 jsr166 1.184 assertNull(h3.join());
2923 jsr166 1.69 rs[3].assertInvoked();
2924     } catch (CompletionException ok) {
2925 jsr166 1.72 checkCompletedWithWrappedException(h3, ex);
2926 jsr166 1.69 rs[3].assertNotInvoked();
2927     }
2928    
2929     checkCompletedNormally(f, v1);
2930 jsr166 1.72 checkCompletedExceptionally(g, ex);
2931 jsr166 1.69 }}
2932    
2933 jsr166 1.65 /**
2934     * runAfterEither result completes exceptionally if either source cancelled
2935     */
2936     public void testRunAfterEither_sourceCancelled() {
2937 jsr166 1.41 for (ExecutionMode m : ExecutionMode.values())
2938 jsr166 1.65 for (boolean mayInterruptIfRunning : new boolean[] { true, false })
2939 jsr166 1.47 for (Integer v1 : new Integer[] { 1, null })
2940     {
2941 jsr166 1.41 final CompletableFuture<Integer> f = new CompletableFuture<>();
2942     final CompletableFuture<Integer> g = new CompletableFuture<>();
2943 jsr166 1.65 final Noop[] rs = new Noop[6];
2944     for (int i = 0; i < rs.length; i++) rs[i] = new Noop(m);
2945 jsr166 1.41
2946 jsr166 1.65 final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
2947     final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
2948     checkIncomplete(h0);
2949     checkIncomplete(h1);
2950     rs[0].assertNotInvoked();
2951     rs[1].assertNotInvoked();
2952     f.cancel(mayInterruptIfRunning);
2953     checkCompletedWithWrappedCancellationException(h0);
2954     checkCompletedWithWrappedCancellationException(h1);
2955     final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
2956     final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
2957     checkCompletedWithWrappedCancellationException(h2);
2958     checkCompletedWithWrappedCancellationException(h3);
2959 jsr166 1.41
2960 jsr166 1.78 assertTrue(g.complete(v1));
2961 jsr166 1.41
2962 jsr166 1.65 // unspecified behavior - both source completions available
2963     final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
2964     final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
2965 jsr166 1.41 try {
2966 jsr166 1.65 assertNull(h4.join());
2967     rs[4].assertInvoked();
2968 jsr166 1.41 } catch (CompletionException ok) {
2969 jsr166 1.65 checkCompletedWithWrappedCancellationException(h4);
2970     rs[4].assertNotInvoked();
2971 jsr166 1.41 }
2972     try {
2973 jsr166 1.65 assertNull(h5.join());
2974     rs[5].assertInvoked();
2975 jsr166 1.41 } catch (CompletionException ok) {
2976 jsr166 1.65 checkCompletedWithWrappedCancellationException(h5);
2977     rs[5].assertNotInvoked();
2978 jsr166 1.41 }
2979 dl 1.5
2980 jsr166 1.65 checkCancelled(f);
2981 jsr166 1.41 checkCompletedNormally(g, v1);
2982 jsr166 1.65 checkCompletedWithWrappedCancellationException(h0);
2983     checkCompletedWithWrappedCancellationException(h1);
2984     checkCompletedWithWrappedCancellationException(h2);
2985     checkCompletedWithWrappedCancellationException(h3);
2986     for (int i = 0; i < 4; i++) rs[i].assertNotInvoked();
2987 jsr166 1.47 }}
2988 dl 1.5
2989     /**
2990     * runAfterEither result completes exceptionally if action does
2991     */
2992 jsr166 1.65 public void testRunAfterEither_actionFailed() {
2993 jsr166 1.41 for (ExecutionMode m : ExecutionMode.values())
2994     for (Integer v1 : new Integer[] { 1, null })
2995 jsr166 1.47 for (Integer v2 : new Integer[] { 2, null })
2996     {
2997 jsr166 1.41 final CompletableFuture<Integer> f = new CompletableFuture<>();
2998     final CompletableFuture<Integer> g = new CompletableFuture<>();
2999 jsr166 1.65 final FailingRunnable[] rs = new FailingRunnable[6];
3000     for (int i = 0; i < rs.length; i++) rs[i] = new FailingRunnable(m);
3001 jsr166 1.41
3002 jsr166 1.65 final CompletableFuture<Void> h0 = m.runAfterEither(f, g, rs[0]);
3003     final CompletableFuture<Void> h1 = m.runAfterEither(g, f, rs[1]);
3004 jsr166 1.78 assertTrue(f.complete(v1));
3005 jsr166 1.65 final CompletableFuture<Void> h2 = m.runAfterEither(f, g, rs[2]);
3006     final CompletableFuture<Void> h3 = m.runAfterEither(g, f, rs[3]);
3007 jsr166 1.151 checkCompletedWithWrappedException(h0, rs[0].ex);
3008     checkCompletedWithWrappedException(h1, rs[1].ex);
3009     checkCompletedWithWrappedException(h2, rs[2].ex);
3010     checkCompletedWithWrappedException(h3, rs[3].ex);
3011 jsr166 1.65 for (int i = 0; i < 4; i++) rs[i].assertInvoked();
3012 jsr166 1.78 assertTrue(g.complete(v2));
3013 jsr166 1.65 final CompletableFuture<Void> h4 = m.runAfterEither(f, g, rs[4]);
3014     final CompletableFuture<Void> h5 = m.runAfterEither(g, f, rs[5]);
3015 jsr166 1.151 checkCompletedWithWrappedException(h4, rs[4].ex);
3016     checkCompletedWithWrappedException(h5, rs[5].ex);
3017 jsr166 1.41
3018     checkCompletedNormally(f, v1);
3019     checkCompletedNormally(g, v2);
3020 jsr166 1.65 for (int i = 0; i < 6; i++) rs[i].assertInvoked();
3021 jsr166 1.47 }}
3022 dl 1.5
3023     /**
3024     * thenCompose result completes normally after normal completion of source
3025     */
3026 jsr166 1.48 public void testThenCompose_normalCompletion() {
3027 jsr166 1.44 for (ExecutionMode m : ExecutionMode.values())
3028 jsr166 1.48 for (boolean createIncomplete : new boolean[] { true, false })
3029 jsr166 1.47 for (Integer v1 : new Integer[] { 1, null })
3030     {
3031 jsr166 1.44 final CompletableFuture<Integer> f = new CompletableFuture<>();
3032 jsr166 1.56 final CompletableFutureInc r = new CompletableFutureInc(m);
3033 jsr166 1.78 if (!createIncomplete) assertTrue(f.complete(v1));
3034 jsr166 1.56 final CompletableFuture<Integer> g = m.thenCompose(f, r);
3035 jsr166 1.78 if (createIncomplete) assertTrue(f.complete(v1));
3036 jsr166 1.21
3037 jsr166 1.44 checkCompletedNormally(g, inc(v1));
3038     checkCompletedNormally(f, v1);
3039 jsr166 1.70 r.assertValue(v1);
3040 jsr166 1.47 }}
3041 dl 1.5
3042     /**
3043     * thenCompose result completes exceptionally after exceptional
3044     * completion of source
3045     */
3046 jsr166 1.48 public void testThenCompose_exceptionalCompletion() {
3047 jsr166 1.47 for (ExecutionMode m : ExecutionMode.values())
3048 jsr166 1.48 for (boolean createIncomplete : new boolean[] { true, false })
3049 jsr166 1.47 {
3050 jsr166 1.44 final CFException ex = new CFException();
3051 jsr166 1.56 final CompletableFutureInc r = new CompletableFutureInc(m);
3052 jsr166 1.44 final CompletableFuture<Integer> f = new CompletableFuture<>();
3053 jsr166 1.48 if (!createIncomplete) f.completeExceptionally(ex);
3054 jsr166 1.56 final CompletableFuture<Integer> g = m.thenCompose(f, r);
3055 jsr166 1.48 if (createIncomplete) f.completeExceptionally(ex);
3056 jsr166 1.21
3057 jsr166 1.72 checkCompletedWithWrappedException(g, ex);
3058     checkCompletedExceptionally(f, ex);
3059 jsr166 1.62 r.assertNotInvoked();
3060 jsr166 1.47 }}
3061 dl 1.5
3062     /**
3063     * thenCompose result completes exceptionally if action does
3064     */
3065 jsr166 1.48 public void testThenCompose_actionFailed() {
3066 jsr166 1.44 for (ExecutionMode m : ExecutionMode.values())
3067 jsr166 1.48 for (boolean createIncomplete : new boolean[] { true, false })
3068 jsr166 1.47 for (Integer v1 : new Integer[] { 1, null })
3069     {
3070 jsr166 1.44 final CompletableFuture<Integer> f = new CompletableFuture<>();
3071     final FailingCompletableFutureFunction r
3072 jsr166 1.56 = new FailingCompletableFutureFunction(m);
3073 jsr166 1.78 if (!createIncomplete) assertTrue(f.complete(v1));
3074 jsr166 1.56 final CompletableFuture<Integer> g = m.thenCompose(f, r);
3075 jsr166 1.78 if (createIncomplete) assertTrue(f.complete(v1));
3076 jsr166 1.44
3077 jsr166 1.151 checkCompletedWithWrappedException(g, r.ex);
3078 jsr166 1.44 checkCompletedNormally(f, v1);
3079 jsr166 1.47 }}
3080 dl 1.5
3081     /**
3082     * thenCompose result completes exceptionally if source cancelled
3083     */
3084 jsr166 1.48 public void testThenCompose_sourceCancelled() {
3085 jsr166 1.44 for (ExecutionMode m : ExecutionMode.values())
3086 jsr166 1.48 for (boolean createIncomplete : new boolean[] { true, false })
3087 jsr166 1.47 for (boolean mayInterruptIfRunning : new boolean[] { true, false })
3088     {
3089 jsr166 1.44 final CompletableFuture<Integer> f = new CompletableFuture<>();
3090 jsr166 1.56 final CompletableFutureInc r = new CompletableFutureInc(m);
3091 jsr166 1.48 if (!createIncomplete) assertTrue(f.cancel(mayInterruptIfRunning));
3092 jsr166 1.56 final CompletableFuture<Integer> g = m.thenCompose(f, r);
3093 jsr166 1.50 if (createIncomplete) {
3094     checkIncomplete(g);
3095     assertTrue(f.cancel(mayInterruptIfRunning));
3096     }
3097 jsr166 1.44
3098 dl 1.5 checkCompletedWithWrappedCancellationException(g);
3099 jsr166 1.44 checkCancelled(f);
3100 jsr166 1.47 }}
3101 dl 1.5
3102 jsr166 1.99 /**
3103     * thenCompose result completes exceptionally if the result of the action does
3104     */
3105     public void testThenCompose_actionReturnsFailingFuture() {
3106     for (ExecutionMode m : ExecutionMode.values())
3107     for (int order = 0; order < 6; order++)
3108     for (Integer v1 : new Integer[] { 1, null })
3109     {
3110     final CFException ex = new CFException();
3111     final CompletableFuture<Integer> f = new CompletableFuture<>();
3112     final CompletableFuture<Integer> g = new CompletableFuture<>();
3113     final CompletableFuture<Integer> h;
3114     // Test all permutations of orders
3115     switch (order) {
3116     case 0:
3117     assertTrue(f.complete(v1));
3118     assertTrue(g.completeExceptionally(ex));
3119     h = m.thenCompose(f, (x -> g));
3120     break;
3121     case 1:
3122     assertTrue(f.complete(v1));
3123     h = m.thenCompose(f, (x -> g));
3124     assertTrue(g.completeExceptionally(ex));
3125     break;
3126     case 2:
3127     assertTrue(g.completeExceptionally(ex));
3128     assertTrue(f.complete(v1));
3129     h = m.thenCompose(f, (x -> g));
3130     break;
3131     case 3:
3132     assertTrue(g.completeExceptionally(ex));
3133     h = m.thenCompose(f, (x -> g));
3134     assertTrue(f.complete(v1));
3135     break;
3136     case 4:
3137     h = m.thenCompose(f, (x -> g));
3138     assertTrue(f.complete(v1));
3139     assertTrue(g.completeExceptionally(ex));
3140     break;
3141     case 5:
3142     h = m.thenCompose(f, (x -> g));
3143     assertTrue(f.complete(v1));
3144     assertTrue(g.completeExceptionally(ex));
3145     break;
3146     default: throw new AssertionError();
3147     }
3148    
3149     checkCompletedExceptionally(g, ex);
3150     checkCompletedWithWrappedException(h, ex);
3151     checkCompletedNormally(f, v1);
3152     }}
3153    
3154 dl 1.198 /**
3155     * exceptionallyCompose result completes normally after normal
3156     * completion of source
3157     */
3158     public void testExceptionallyCompose_normalCompletion() {
3159     for (ExecutionMode m : ExecutionMode.values())
3160     for (boolean createIncomplete : new boolean[] { true, false })
3161     for (Integer v1 : new Integer[] { 1, null })
3162     {
3163     final CompletableFuture<Integer> f = new CompletableFuture<>();
3164     final ExceptionalCompletableFutureFunction r =
3165     new ExceptionalCompletableFutureFunction(m);
3166     if (!createIncomplete) assertTrue(f.complete(v1));
3167     final CompletableFuture<Integer> g = m.exceptionallyCompose(f, r);
3168     if (createIncomplete) assertTrue(f.complete(v1));
3169    
3170     checkCompletedNormally(f, v1);
3171     checkCompletedNormally(g, v1);
3172     r.assertNotInvoked();
3173     }}
3174    
3175     /**
3176     * exceptionallyCompose result completes normally after exceptional
3177     * completion of source
3178     */
3179     public void testExceptionallyCompose_exceptionalCompletion() {
3180     for (ExecutionMode m : ExecutionMode.values())
3181     for (boolean createIncomplete : new boolean[] { true, false })
3182     {
3183     final CFException ex = new CFException();
3184     final ExceptionalCompletableFutureFunction r =
3185     new ExceptionalCompletableFutureFunction(m);
3186     final CompletableFuture<Integer> f = new CompletableFuture<>();
3187     if (!createIncomplete) f.completeExceptionally(ex);
3188     final CompletableFuture<Integer> g = m.exceptionallyCompose(f, r);
3189     if (createIncomplete) f.completeExceptionally(ex);
3190    
3191     checkCompletedExceptionally(f, ex);
3192     checkCompletedNormally(g, r.value);
3193     r.assertInvoked();
3194     }}
3195    
3196     /**
3197     * exceptionallyCompose completes exceptionally on exception if action does
3198     */
3199     public void testExceptionallyCompose_actionFailed() {
3200     for (ExecutionMode m : ExecutionMode.values())
3201     for (boolean createIncomplete : new boolean[] { true, false })
3202     for (Integer v1 : new Integer[] { 1, null })
3203     {
3204     final CFException ex = new CFException();
3205     final CompletableFuture<Integer> f = new CompletableFuture<>();
3206     final FailingExceptionalCompletableFutureFunction r
3207     = new FailingExceptionalCompletableFutureFunction(m);
3208     if (!createIncomplete) f.completeExceptionally(ex);
3209     final CompletableFuture<Integer> g = m.exceptionallyCompose(f, r);
3210     if (createIncomplete) f.completeExceptionally(ex);
3211    
3212     checkCompletedExceptionally(f, ex);
3213     checkCompletedWithWrappedException(g, r.ex);
3214     r.assertInvoked();
3215     }}
3216    
3217 jsr166 1.209 /**
3218 jsr166 1.211 * exceptionallyCompose result completes exceptionally if the
3219 jsr166 1.209 * result of the action does
3220     */
3221     public void testExceptionallyCompose_actionReturnsFailingFuture() {
3222     for (ExecutionMode m : ExecutionMode.values())
3223     for (int order = 0; order < 6; order++)
3224     for (Integer v1 : new Integer[] { 1, null })
3225     {
3226     final CFException ex0 = new CFException();
3227     final CFException ex = new CFException();
3228     final CompletableFuture<Integer> f = new CompletableFuture<>();
3229     final CompletableFuture<Integer> g = new CompletableFuture<>();
3230     final CompletableFuture<Integer> h;
3231     // Test all permutations of orders
3232     switch (order) {
3233     case 0:
3234     assertTrue(f.completeExceptionally(ex0));
3235     assertTrue(g.completeExceptionally(ex));
3236     h = m.exceptionallyCompose(f, (x -> g));
3237     break;
3238     case 1:
3239     assertTrue(f.completeExceptionally(ex0));
3240     h = m.exceptionallyCompose(f, (x -> g));
3241     assertTrue(g.completeExceptionally(ex));
3242     break;
3243     case 2:
3244     assertTrue(g.completeExceptionally(ex));
3245     assertTrue(f.completeExceptionally(ex0));
3246     h = m.exceptionallyCompose(f, (x -> g));
3247     break;
3248     case 3:
3249     assertTrue(g.completeExceptionally(ex));
3250     h = m.exceptionallyCompose(f, (x -> g));
3251     assertTrue(f.completeExceptionally(ex0));
3252     break;
3253     case 4:
3254     h = m.exceptionallyCompose(f, (x -> g));
3255     assertTrue(f.completeExceptionally(ex0));
3256     assertTrue(g.completeExceptionally(ex));
3257     break;
3258     case 5:
3259     h = m.exceptionallyCompose(f, (x -> g));
3260     assertTrue(f.completeExceptionally(ex0));
3261     assertTrue(g.completeExceptionally(ex));
3262     break;
3263     default: throw new AssertionError();
3264     }
3265    
3266     checkCompletedExceptionally(g, ex);
3267 jsr166 1.210 checkCompletedWithWrappedException(h, ex);
3268 jsr166 1.209 checkCompletedExceptionally(f, ex0);
3269     }}
3270 dl 1.198
3271 jsr166 1.6 // other static methods
3272 dl 1.5
3273     /**
3274     * allOf(no component futures) returns a future completed normally
3275     * with the value null
3276     */
3277     public void testAllOf_empty() throws Exception {
3278 jsr166 1.24 CompletableFuture<Void> f = CompletableFuture.allOf();
3279 dl 1.5 checkCompletedNormally(f, null);
3280     }
3281    
3282     /**
3283 jsr166 1.25 * allOf returns a future completed normally with the value null
3284     * when all components complete normally
3285 dl 1.5 */
3286 jsr166 1.25 public void testAllOf_normal() throws Exception {
3287 jsr166 1.88 for (int k = 1; k < 10; k++) {
3288 jsr166 1.59 CompletableFuture<Integer>[] fs
3289     = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3290 jsr166 1.86 for (int i = 0; i < k; i++)
3291 jsr166 1.22 fs[i] = new CompletableFuture<>();
3292 dl 1.9 CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3293 jsr166 1.86 for (int i = 0; i < k; i++) {
3294 dl 1.5 checkIncomplete(f);
3295 jsr166 1.24 checkIncomplete(CompletableFuture.allOf(fs));
3296 dl 1.5 fs[i].complete(one);
3297     }
3298 dl 1.9 checkCompletedNormally(f, null);
3299 jsr166 1.24 checkCompletedNormally(CompletableFuture.allOf(fs), null);
3300 dl 1.5 }
3301     }
3302    
3303 jsr166 1.150 public void testAllOf_normal_backwards() throws Exception {
3304 jsr166 1.88 for (int k = 1; k < 10; k++) {
3305 jsr166 1.59 CompletableFuture<Integer>[] fs
3306     = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3307 jsr166 1.86 for (int i = 0; i < k; i++)
3308 jsr166 1.59 fs[i] = new CompletableFuture<>();
3309     CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3310     for (int i = k - 1; i >= 0; i--) {
3311     checkIncomplete(f);
3312     checkIncomplete(CompletableFuture.allOf(fs));
3313     fs[i].complete(one);
3314     }
3315     checkCompletedNormally(f, null);
3316     checkCompletedNormally(CompletableFuture.allOf(fs), null);
3317     }
3318     }
3319    
3320 jsr166 1.88 public void testAllOf_exceptional() throws Exception {
3321     for (int k = 1; k < 10; k++) {
3322     CompletableFuture<Integer>[] fs
3323     = (CompletableFuture<Integer>[]) new CompletableFuture[k];
3324     CFException ex = new CFException();
3325     for (int i = 0; i < k; i++)
3326     fs[i] = new CompletableFuture<>();
3327     CompletableFuture<Void> f = CompletableFuture.allOf(fs);
3328     for (int i = 0; i < k; i++) {
3329     checkIncomplete(f);
3330     checkIncomplete(CompletableFuture.allOf(fs));
3331 jsr166 1.121 if (i != k / 2) {
3332 jsr166 1.88 fs[i].complete(i);
3333     checkCompletedNormally(fs[i], i);
3334     } else {
3335     fs[i].completeExceptionally(ex);
3336     checkCompletedExceptionally(fs[i], ex);
3337     }
3338     }
3339     checkCompletedWithWrappedException(f, ex);
3340     checkCompletedWithWrappedException(CompletableFuture.allOf(fs), ex);
3341     }
3342     }
3343    
3344 dl 1.5 /**
3345     * anyOf(no component futures) returns an incomplete future
3346     */
3347     public void testAnyOf_empty() throws Exception {
3348 jsr166 1.86 for (Integer v1 : new Integer[] { 1, null })
3349     {
3350 jsr166 1.24 CompletableFuture<Object> f = CompletableFuture.anyOf();
3351 dl 1.5 checkIncomplete(f);
3352 jsr166 1.86
3353     f.complete(v1);
3354     checkCompletedNormally(f, v1);
3355     }}
3356 dl 1.5
3357     /**
3358 jsr166 1.25 * anyOf returns a future completed normally with a value when
3359     * a component future does
3360 dl 1.5 */
3361 jsr166 1.24 public void testAnyOf_normal() throws Exception {
3362 jsr166 1.86 for (int k = 0; k < 10; k++) {
3363 dl 1.5 CompletableFuture[] fs = new CompletableFuture[k];
3364 jsr166 1.86 for (int i = 0; i < k; i++)
3365 jsr166 1.22 fs[i] = new CompletableFuture<>();
3366 dl 1.9 CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3367 dl 1.5 checkIncomplete(f);
3368 jsr166 1.86 for (int i = 0; i < k; i++) {
3369     fs[i].complete(i);
3370     checkCompletedNormally(f, 0);
3371     int x = (int) CompletableFuture.anyOf(fs).join();
3372     assertTrue(0 <= x && x <= i);
3373     }
3374     }
3375     }
3376     public void testAnyOf_normal_backwards() throws Exception {
3377     for (int k = 0; k < 10; k++) {
3378     CompletableFuture[] fs = new CompletableFuture[k];
3379     for (int i = 0; i < k; i++)
3380     fs[i] = new CompletableFuture<>();
3381     CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3382     checkIncomplete(f);
3383     for (int i = k - 1; i >= 0; i--) {
3384     fs[i].complete(i);
3385     checkCompletedNormally(f, k - 1);
3386     int x = (int) CompletableFuture.anyOf(fs).join();
3387     assertTrue(i <= x && x <= k - 1);
3388 jsr166 1.24 }
3389     }
3390     }
3391    
3392     /**
3393     * anyOf result completes exceptionally when any component does.
3394     */
3395     public void testAnyOf_exceptional() throws Exception {
3396 jsr166 1.86 for (int k = 0; k < 10; k++) {
3397 jsr166 1.24 CompletableFuture[] fs = new CompletableFuture[k];
3398 jsr166 1.87 CFException[] exs = new CFException[k];
3399     for (int i = 0; i < k; i++) {
3400 jsr166 1.24 fs[i] = new CompletableFuture<>();
3401 jsr166 1.87 exs[i] = new CFException();
3402     }
3403 jsr166 1.24 CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3404     checkIncomplete(f);
3405 jsr166 1.86 for (int i = 0; i < k; i++) {
3406 jsr166 1.87 fs[i].completeExceptionally(exs[i]);
3407     checkCompletedWithWrappedException(f, exs[0]);
3408     checkCompletedWithWrappedCFException(CompletableFuture.anyOf(fs));
3409     }
3410     }
3411     }
3412    
3413     public void testAnyOf_exceptional_backwards() throws Exception {
3414     for (int k = 0; k < 10; k++) {
3415     CompletableFuture[] fs = new CompletableFuture[k];
3416     CFException[] exs = new CFException[k];
3417     for (int i = 0; i < k; i++) {
3418     fs[i] = new CompletableFuture<>();
3419     exs[i] = new CFException();
3420     }
3421     CompletableFuture<Object> f = CompletableFuture.anyOf(fs);
3422     checkIncomplete(f);
3423     for (int i = k - 1; i >= 0; i--) {
3424     fs[i].completeExceptionally(exs[i]);
3425     checkCompletedWithWrappedException(f, exs[k - 1]);
3426 jsr166 1.24 checkCompletedWithWrappedCFException(CompletableFuture.anyOf(fs));
3427 dl 1.5 }
3428     }
3429     }
3430    
3431     /**
3432     * Completion methods throw NullPointerException with null arguments
3433     */
3434 jsr166 1.186 @SuppressWarnings("FutureReturnValueIgnored")
3435 dl 1.5 public void testNPE() {
3436 jsr166 1.22 CompletableFuture<Integer> f = new CompletableFuture<>();
3437     CompletableFuture<Integer> g = new CompletableFuture<>();
3438 jsr166 1.14 CompletableFuture<Integer> nullFuture = (CompletableFuture<Integer>)null;
3439 jsr166 1.17 ThreadExecutor exec = new ThreadExecutor();
3440 jsr166 1.14
3441     Runnable[] throwingActions = {
3442 jsr166 1.31 () -> CompletableFuture.supplyAsync(null),
3443     () -> CompletableFuture.supplyAsync(null, exec),
3444 jsr166 1.95 () -> CompletableFuture.supplyAsync(new IntegerSupplier(ExecutionMode.SYNC, 42), null),
3445 jsr166 1.31
3446     () -> CompletableFuture.runAsync(null),
3447     () -> CompletableFuture.runAsync(null, exec),
3448     () -> CompletableFuture.runAsync(() -> {}, null),
3449    
3450     () -> f.completeExceptionally(null),
3451    
3452     () -> f.thenApply(null),
3453     () -> f.thenApplyAsync(null),
3454 jsr166 1.180 () -> f.thenApplyAsync(x -> x, null),
3455 jsr166 1.31 () -> f.thenApplyAsync(null, exec),
3456    
3457     () -> f.thenAccept(null),
3458     () -> f.thenAcceptAsync(null),
3459 jsr166 1.180 () -> f.thenAcceptAsync(x -> {} , null),
3460 jsr166 1.31 () -> f.thenAcceptAsync(null, exec),
3461    
3462     () -> f.thenRun(null),
3463     () -> f.thenRunAsync(null),
3464     () -> f.thenRunAsync(() -> {} , null),
3465     () -> f.thenRunAsync(null, exec),
3466    
3467     () -> f.thenCombine(g, null),
3468     () -> f.thenCombineAsync(g, null),
3469     () -> f.thenCombineAsync(g, null, exec),
3470     () -> f.thenCombine(nullFuture, (x, y) -> x),
3471     () -> f.thenCombineAsync(nullFuture, (x, y) -> x),
3472     () -> f.thenCombineAsync(nullFuture, (x, y) -> x, exec),
3473     () -> f.thenCombineAsync(g, (x, y) -> x, null),
3474    
3475     () -> f.thenAcceptBoth(g, null),
3476     () -> f.thenAcceptBothAsync(g, null),
3477     () -> f.thenAcceptBothAsync(g, null, exec),
3478     () -> f.thenAcceptBoth(nullFuture, (x, y) -> {}),
3479     () -> f.thenAcceptBothAsync(nullFuture, (x, y) -> {}),
3480     () -> f.thenAcceptBothAsync(nullFuture, (x, y) -> {}, exec),
3481     () -> f.thenAcceptBothAsync(g, (x, y) -> {}, null),
3482    
3483     () -> f.runAfterBoth(g, null),
3484     () -> f.runAfterBothAsync(g, null),
3485     () -> f.runAfterBothAsync(g, null, exec),
3486     () -> f.runAfterBoth(nullFuture, () -> {}),
3487     () -> f.runAfterBothAsync(nullFuture, () -> {}),
3488     () -> f.runAfterBothAsync(nullFuture, () -> {}, exec),
3489     () -> f.runAfterBothAsync(g, () -> {}, null),
3490    
3491     () -> f.applyToEither(g, null),
3492     () -> f.applyToEitherAsync(g, null),
3493     () -> f.applyToEitherAsync(g, null, exec),
3494 jsr166 1.180 () -> f.applyToEither(nullFuture, x -> x),
3495     () -> f.applyToEitherAsync(nullFuture, x -> x),
3496     () -> f.applyToEitherAsync(nullFuture, x -> x, exec),
3497     () -> f.applyToEitherAsync(g, x -> x, null),
3498 jsr166 1.31
3499     () -> f.acceptEither(g, null),
3500     () -> f.acceptEitherAsync(g, null),
3501     () -> f.acceptEitherAsync(g, null, exec),
3502 jsr166 1.180 () -> f.acceptEither(nullFuture, x -> {}),
3503     () -> f.acceptEitherAsync(nullFuture, x -> {}),
3504     () -> f.acceptEitherAsync(nullFuture, x -> {}, exec),
3505     () -> f.acceptEitherAsync(g, x -> {}, null),
3506 jsr166 1.31
3507     () -> f.runAfterEither(g, null),
3508     () -> f.runAfterEitherAsync(g, null),
3509     () -> f.runAfterEitherAsync(g, null, exec),
3510     () -> f.runAfterEither(nullFuture, () -> {}),
3511     () -> f.runAfterEitherAsync(nullFuture, () -> {}),
3512     () -> f.runAfterEitherAsync(nullFuture, () -> {}, exec),
3513     () -> f.runAfterEitherAsync(g, () -> {}, null),
3514    
3515     () -> f.thenCompose(null),
3516     () -> f.thenComposeAsync(null),
3517 jsr166 1.56 () -> f.thenComposeAsync(new CompletableFutureInc(ExecutionMode.EXECUTOR), null),
3518 jsr166 1.31 () -> f.thenComposeAsync(null, exec),
3519    
3520     () -> f.exceptionally(null),
3521    
3522     () -> f.handle(null),
3523 jsr166 1.107
3524 jsr166 1.31 () -> CompletableFuture.allOf((CompletableFuture<?>)null),
3525     () -> CompletableFuture.allOf((CompletableFuture<?>[])null),
3526     () -> CompletableFuture.allOf(f, null),
3527     () -> CompletableFuture.allOf(null, f),
3528    
3529     () -> CompletableFuture.anyOf((CompletableFuture<?>)null),
3530     () -> CompletableFuture.anyOf((CompletableFuture<?>[])null),
3531     () -> CompletableFuture.anyOf(f, null),
3532     () -> CompletableFuture.anyOf(null, f),
3533 jsr166 1.32
3534     () -> f.obtrudeException(null),
3535 jsr166 1.115
3536     () -> CompletableFuture.delayedExecutor(1L, SECONDS, null),
3537 jsr166 1.143 () -> CompletableFuture.delayedExecutor(1L, null, exec),
3538 jsr166 1.115 () -> CompletableFuture.delayedExecutor(1L, null),
3539 jsr166 1.116
3540     () -> f.orTimeout(1L, null),
3541     () -> f.completeOnTimeout(42, 1L, null),
3542 jsr166 1.121
3543     () -> CompletableFuture.failedFuture(null),
3544     () -> CompletableFuture.failedStage(null),
3545 jsr166 1.14 };
3546 dl 1.5
3547 jsr166 1.14 assertThrows(NullPointerException.class, throwingActions);
3548 jsr166 1.17 assertEquals(0, exec.count.get());
3549 dl 1.5 }
3550    
3551 dl 1.26 /**
3552 jsr166 1.152 * Test submissions to an executor that rejects all tasks.
3553     */
3554     public void testRejectingExecutor() {
3555 jsr166 1.161 for (Integer v : new Integer[] { 1, null })
3556     {
3557 jsr166 1.154 final CountingRejectingExecutor e = new CountingRejectingExecutor();
3558 jsr166 1.152
3559     final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3560     final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3561    
3562     List<CompletableFuture<?>> futures = new ArrayList<>();
3563    
3564     List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3565     srcs.add(complete);
3566     srcs.add(incomplete);
3567    
3568     for (CompletableFuture<Integer> src : srcs) {
3569     List<CompletableFuture<?>> fs = new ArrayList<>();
3570     fs.add(src.thenRunAsync(() -> {}, e));
3571 jsr166 1.180 fs.add(src.thenAcceptAsync(z -> {}, e));
3572     fs.add(src.thenApplyAsync(z -> z, e));
3573 jsr166 1.152
3574     fs.add(src.thenCombineAsync(src, (x, y) -> x, e));
3575     fs.add(src.thenAcceptBothAsync(src, (x, y) -> {}, e));
3576     fs.add(src.runAfterBothAsync(src, () -> {}, e));
3577    
3578 jsr166 1.180 fs.add(src.applyToEitherAsync(src, z -> z, e));
3579     fs.add(src.acceptEitherAsync(src, z -> {}, e));
3580 jsr166 1.152 fs.add(src.runAfterEitherAsync(src, () -> {}, e));
3581    
3582 jsr166 1.180 fs.add(src.thenComposeAsync(z -> null, e));
3583 jsr166 1.152 fs.add(src.whenCompleteAsync((z, t) -> {}, e));
3584     fs.add(src.handleAsync((z, t) -> null, e));
3585    
3586     for (CompletableFuture<?> future : fs) {
3587     if (src.isDone())
3588 jsr166 1.154 checkCompletedWithWrappedException(future, e.ex);
3589 jsr166 1.152 else
3590     checkIncomplete(future);
3591     }
3592     futures.addAll(fs);
3593     }
3594    
3595     {
3596     List<CompletableFuture<?>> fs = new ArrayList<>();
3597    
3598     fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3599     fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3600    
3601     fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3602     fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3603    
3604     fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3605     fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3606    
3607     for (CompletableFuture<?> future : fs)
3608     checkIncomplete(future);
3609     futures.addAll(fs);
3610     }
3611    
3612     {
3613     List<CompletableFuture<?>> fs = new ArrayList<>();
3614    
3615 jsr166 1.180 fs.add(complete.applyToEitherAsync(incomplete, z -> z, e));
3616     fs.add(incomplete.applyToEitherAsync(complete, z -> z, e));
3617 jsr166 1.152
3618 jsr166 1.180 fs.add(complete.acceptEitherAsync(incomplete, z -> {}, e));
3619     fs.add(incomplete.acceptEitherAsync(complete, z -> {}, e));
3620 jsr166 1.152
3621     fs.add(complete.runAfterEitherAsync(incomplete, () -> {}, e));
3622     fs.add(incomplete.runAfterEitherAsync(complete, () -> {}, e));
3623    
3624     for (CompletableFuture<?> future : fs)
3625 jsr166 1.154 checkCompletedWithWrappedException(future, e.ex);
3626 jsr166 1.152 futures.addAll(fs);
3627     }
3628    
3629     incomplete.complete(v);
3630    
3631     for (CompletableFuture<?> future : futures)
3632 jsr166 1.154 checkCompletedWithWrappedException(future, e.ex);
3633    
3634     assertEquals(futures.size(), e.count.get());
3635 jsr166 1.161 }}
3636 jsr166 1.152
3637     /**
3638 jsr166 1.153 * Test submissions to an executor that rejects all tasks, but
3639     * should never be invoked because the dependent future is
3640     * explicitly completed.
3641     */
3642     public void testRejectingExecutorNeverInvoked() {
3643 jsr166 1.161 for (Integer v : new Integer[] { 1, null })
3644     {
3645 jsr166 1.153 final CountingRejectingExecutor e = new CountingRejectingExecutor();
3646    
3647     final CompletableFuture<Integer> complete = CompletableFuture.completedFuture(v);
3648     final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
3649    
3650     List<CompletableFuture<?>> futures = new ArrayList<>();
3651    
3652     List<CompletableFuture<Integer>> srcs = new ArrayList<>();
3653     srcs.add(complete);
3654     srcs.add(incomplete);
3655    
3656     List<CompletableFuture<?>> fs = new ArrayList<>();
3657     fs.add(incomplete.thenRunAsync(() -> {}, e));
3658 jsr166 1.180 fs.add(incomplete.thenAcceptAsync(z -> {}, e));
3659     fs.add(incomplete.thenApplyAsync(z -> z, e));
3660 jsr166 1.153
3661     fs.add(incomplete.thenCombineAsync(incomplete, (x, y) -> x, e));
3662     fs.add(incomplete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3663     fs.add(incomplete.runAfterBothAsync(incomplete, () -> {}, e));
3664    
3665 jsr166 1.180 fs.add(incomplete.applyToEitherAsync(incomplete, z -> z, e));
3666     fs.add(incomplete.acceptEitherAsync(incomplete, z -> {}, e));
3667 jsr166 1.153 fs.add(incomplete.runAfterEitherAsync(incomplete, () -> {}, e));
3668    
3669 jsr166 1.180 fs.add(incomplete.thenComposeAsync(z -> null, e));
3670 jsr166 1.153 fs.add(incomplete.whenCompleteAsync((z, t) -> {}, e));
3671     fs.add(incomplete.handleAsync((z, t) -> null, e));
3672    
3673     fs.add(complete.thenCombineAsync(incomplete, (x, y) -> x, e));
3674     fs.add(incomplete.thenCombineAsync(complete, (x, y) -> x, e));
3675    
3676     fs.add(complete.thenAcceptBothAsync(incomplete, (x, y) -> {}, e));
3677     fs.add(incomplete.thenAcceptBothAsync(complete, (x, y) -> {}, e));
3678    
3679     fs.add(complete.runAfterBothAsync(incomplete, () -> {}, e));
3680     fs.add(incomplete.runAfterBothAsync(complete, () -> {}, e));
3681    
3682     for (CompletableFuture<?> future : fs)
3683     checkIncomplete(future);
3684    
3685     for (CompletableFuture<?> future : fs)
3686     future.complete(null);
3687    
3688     incomplete.complete(v);
3689    
3690     for (CompletableFuture<?> future : fs)
3691     checkCompletedNormally(future, null);
3692    
3693     assertEquals(0, e.count.get());
3694 jsr166 1.161 }}
3695 jsr166 1.153
3696     /**
3697 dl 1.26 * toCompletableFuture returns this CompletableFuture.
3698     */
3699     public void testToCompletableFuture() {
3700     CompletableFuture<Integer> f = new CompletableFuture<>();
3701     assertSame(f, f.toCompletableFuture());
3702     }
3703    
3704 dl 1.103 // jdk9
3705 jsr166 1.104
3706 dl 1.103 /**
3707     * newIncompleteFuture returns an incomplete CompletableFuture
3708     */
3709     public void testNewIncompleteFuture() {
3710 jsr166 1.117 for (Integer v1 : new Integer[] { 1, null })
3711     {
3712 dl 1.103 CompletableFuture<Integer> f = new CompletableFuture<>();
3713     CompletableFuture<Integer> g = f.newIncompleteFuture();
3714     checkIncomplete(f);
3715     checkIncomplete(g);
3716 jsr166 1.117 f.complete(v1);
3717     checkCompletedNormally(f, v1);
3718     checkIncomplete(g);
3719     g.complete(v1);
3720     checkCompletedNormally(g, v1);
3721     assertSame(g.getClass(), CompletableFuture.class);
3722     }}
3723 dl 1.103
3724     /**
3725     * completedStage returns a completed CompletionStage
3726     */
3727     public void testCompletedStage() {
3728 jsr166 1.120 AtomicInteger x = new AtomicInteger(0);
3729 jsr166 1.183 AtomicReference<Throwable> r = new AtomicReference<>();
3730 dl 1.103 CompletionStage<Integer> f = CompletableFuture.completedStage(1);
3731     f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3732     assertEquals(x.get(), 1);
3733     assertNull(r.get());
3734     }
3735    
3736     /**
3737     * defaultExecutor by default returns the commonPool if
3738 dl 1.110 * it supports more than one thread.
3739 dl 1.103 */
3740     public void testDefaultExecutor() {
3741     CompletableFuture<Integer> f = new CompletableFuture<>();
3742     Executor e = f.defaultExecutor();
3743 jsr166 1.108 Executor c = ForkJoinPool.commonPool();
3744 dl 1.105 if (ForkJoinPool.getCommonPoolParallelism() > 1)
3745 dl 1.103 assertSame(e, c);
3746 jsr166 1.111 else
3747     assertNotSame(e, c);
3748 dl 1.103 }
3749    
3750     /**
3751     * failedFuture returns a CompletableFuture completed
3752     * exceptionally with the given Exception
3753     */
3754     public void testFailedFuture() {
3755     CFException ex = new CFException();
3756     CompletableFuture<Integer> f = CompletableFuture.failedFuture(ex);
3757 jsr166 1.119 checkCompletedExceptionally(f, ex);
3758 dl 1.103 }
3759    
3760     /**
3761     * failedFuture(null) throws NPE
3762     */
3763 jsr166 1.118 public void testFailedFuture_null() {
3764 dl 1.103 try {
3765     CompletableFuture<Integer> f = CompletableFuture.failedFuture(null);
3766 jsr166 1.104 shouldThrow();
3767     } catch (NullPointerException success) {}
3768 dl 1.103 }
3769    
3770     /**
3771     * copy returns a CompletableFuture that is completed normally,
3772     * with the same value, when source is.
3773     */
3774 jsr166 1.174 public void testCopy_normalCompletion() {
3775     for (boolean createIncomplete : new boolean[] { true, false })
3776     for (Integer v1 : new Integer[] { 1, null })
3777     {
3778 dl 1.103 CompletableFuture<Integer> f = new CompletableFuture<>();
3779 jsr166 1.174 if (!createIncomplete) assertTrue(f.complete(v1));
3780 dl 1.103 CompletableFuture<Integer> g = f.copy();
3781 jsr166 1.174 if (createIncomplete) {
3782     checkIncomplete(f);
3783     checkIncomplete(g);
3784     assertTrue(f.complete(v1));
3785     }
3786     checkCompletedNormally(f, v1);
3787     checkCompletedNormally(g, v1);
3788     }}
3789 dl 1.103
3790     /**
3791     * copy returns a CompletableFuture that is completed exceptionally
3792     * when source is.
3793     */
3794 jsr166 1.174 public void testCopy_exceptionalCompletion() {
3795     for (boolean createIncomplete : new boolean[] { true, false })
3796     {
3797     CFException ex = new CFException();
3798 dl 1.103 CompletableFuture<Integer> f = new CompletableFuture<>();
3799 jsr166 1.174 if (!createIncomplete) f.completeExceptionally(ex);
3800 dl 1.103 CompletableFuture<Integer> g = f.copy();
3801 jsr166 1.174 if (createIncomplete) {
3802     checkIncomplete(f);
3803     checkIncomplete(g);
3804     f.completeExceptionally(ex);
3805     }
3806 dl 1.103 checkCompletedExceptionally(f, ex);
3807 jsr166 1.121 checkCompletedWithWrappedException(g, ex);
3808 jsr166 1.174 }}
3809    
3810     /**
3811     * Completion of a copy does not complete its source.
3812     */
3813     public void testCopy_oneWayPropagation() {
3814     CompletableFuture<Integer> f = new CompletableFuture<>();
3815     assertTrue(f.copy().complete(1));
3816     assertTrue(f.copy().complete(null));
3817     assertTrue(f.copy().cancel(true));
3818     assertTrue(f.copy().cancel(false));
3819     assertTrue(f.copy().completeExceptionally(new CFException()));
3820     checkIncomplete(f);
3821 dl 1.103 }
3822    
3823     /**
3824     * minimalCompletionStage returns a CompletableFuture that is
3825     * completed normally, with the same value, when source is.
3826     */
3827     public void testMinimalCompletionStage() {
3828     CompletableFuture<Integer> f = new CompletableFuture<>();
3829     CompletionStage<Integer> g = f.minimalCompletionStage();
3830 jsr166 1.120 AtomicInteger x = new AtomicInteger(0);
3831 jsr166 1.183 AtomicReference<Throwable> r = new AtomicReference<>();
3832 dl 1.103 checkIncomplete(f);
3833     g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3834     f.complete(1);
3835     checkCompletedNormally(f, 1);
3836     assertEquals(x.get(), 1);
3837     assertNull(r.get());
3838     }
3839    
3840     /**
3841     * minimalCompletionStage returns a CompletableFuture that is
3842     * completed exceptionally when source is.
3843     */
3844     public void testMinimalCompletionStage2() {
3845     CompletableFuture<Integer> f = new CompletableFuture<>();
3846     CompletionStage<Integer> g = f.minimalCompletionStage();
3847 jsr166 1.120 AtomicInteger x = new AtomicInteger(0);
3848 jsr166 1.183 AtomicReference<Throwable> r = new AtomicReference<>();
3849 dl 1.103 g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3850     checkIncomplete(f);
3851     CFException ex = new CFException();
3852     f.completeExceptionally(ex);
3853     checkCompletedExceptionally(f, ex);
3854     assertEquals(x.get(), 0);
3855     assertEquals(r.get().getCause(), ex);
3856     }
3857    
3858     /**
3859 jsr166 1.109 * failedStage returns a CompletionStage completed
3860 dl 1.103 * exceptionally with the given Exception
3861     */
3862     public void testFailedStage() {
3863     CFException ex = new CFException();
3864     CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
3865 jsr166 1.120 AtomicInteger x = new AtomicInteger(0);
3866 jsr166 1.183 AtomicReference<Throwable> r = new AtomicReference<>();
3867 dl 1.103 f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
3868     assertEquals(x.get(), 0);
3869 jsr166 1.119 assertEquals(r.get(), ex);
3870 dl 1.103 }
3871    
3872     /**
3873     * completeAsync completes with value of given supplier
3874     */
3875     public void testCompleteAsync() {
3876 jsr166 1.121 for (Integer v1 : new Integer[] { 1, null })
3877     {
3878 dl 1.103 CompletableFuture<Integer> f = new CompletableFuture<>();
3879 jsr166 1.121 f.completeAsync(() -> v1);
3880 dl 1.103 f.join();
3881 jsr166 1.121 checkCompletedNormally(f, v1);
3882     }}
3883 dl 1.103
3884     /**
3885     * completeAsync completes exceptionally if given supplier throws
3886     */
3887     public void testCompleteAsync2() {
3888     CompletableFuture<Integer> f = new CompletableFuture<>();
3889     CFException ex = new CFException();
3890 jsr166 1.181 f.completeAsync(() -> { throw ex; });
3891 dl 1.103 try {
3892     f.join();
3893     shouldThrow();
3894 jsr166 1.121 } catch (CompletionException success) {}
3895     checkCompletedWithWrappedException(f, ex);
3896 dl 1.103 }
3897    
3898     /**
3899     * completeAsync with given executor completes with value of given supplier
3900     */
3901     public void testCompleteAsync3() {
3902 jsr166 1.121 for (Integer v1 : new Integer[] { 1, null })
3903     {
3904 dl 1.103 CompletableFuture<Integer> f = new CompletableFuture<>();
3905 jsr166 1.121 ThreadExecutor executor = new ThreadExecutor();
3906     f.completeAsync(() -> v1, executor);
3907     assertSame(v1, f.join());
3908     checkCompletedNormally(f, v1);
3909     assertEquals(1, executor.count.get());
3910     }}
3911 dl 1.103
3912     /**
3913     * completeAsync with given executor completes exceptionally if
3914     * given supplier throws
3915     */
3916     public void testCompleteAsync4() {
3917     CompletableFuture<Integer> f = new CompletableFuture<>();
3918     CFException ex = new CFException();
3919 jsr166 1.121 ThreadExecutor executor = new ThreadExecutor();
3920 jsr166 1.181 f.completeAsync(() -> { throw ex; }, executor);
3921 dl 1.103 try {
3922     f.join();
3923     shouldThrow();
3924 jsr166 1.121 } catch (CompletionException success) {}
3925     checkCompletedWithWrappedException(f, ex);
3926     assertEquals(1, executor.count.get());
3927 dl 1.103 }
3928    
3929     /**
3930 jsr166 1.106 * orTimeout completes with TimeoutException if not complete
3931 dl 1.103 */
3932 jsr166 1.121 public void testOrTimeout_timesOut() {
3933     long timeoutMillis = timeoutMillis();
3934 dl 1.103 CompletableFuture<Integer> f = new CompletableFuture<>();
3935 jsr166 1.121 long startTime = System.nanoTime();
3936 jsr166 1.145 assertSame(f, f.orTimeout(timeoutMillis, MILLISECONDS));
3937 jsr166 1.121 checkCompletedWithTimeoutException(f);
3938     assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3939 dl 1.103 }
3940    
3941     /**
3942 jsr166 1.106 * orTimeout completes normally if completed before timeout
3943 dl 1.103 */
3944 jsr166 1.121 public void testOrTimeout_completed() {
3945     for (Integer v1 : new Integer[] { 1, null })
3946     {
3947 dl 1.103 CompletableFuture<Integer> f = new CompletableFuture<>();
3948 jsr166 1.121 CompletableFuture<Integer> g = new CompletableFuture<>();
3949     long startTime = System.nanoTime();
3950     f.complete(v1);
3951 jsr166 1.145 assertSame(f, f.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3952     assertSame(g, g.orTimeout(LONG_DELAY_MS, MILLISECONDS));
3953 jsr166 1.121 g.complete(v1);
3954     checkCompletedNormally(f, v1);
3955     checkCompletedNormally(g, v1);
3956     assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3957     }}
3958 dl 1.103
3959     /**
3960 jsr166 1.106 * completeOnTimeout completes with given value if not complete
3961 dl 1.103 */
3962 jsr166 1.121 public void testCompleteOnTimeout_timesOut() {
3963     testInParallel(() -> testCompleteOnTimeout_timesOut(42),
3964     () -> testCompleteOnTimeout_timesOut(null));
3965     }
3966    
3967 jsr166 1.146 /**
3968     * completeOnTimeout completes with given value if not complete
3969     */
3970 jsr166 1.121 public void testCompleteOnTimeout_timesOut(Integer v) {
3971     long timeoutMillis = timeoutMillis();
3972 dl 1.103 CompletableFuture<Integer> f = new CompletableFuture<>();
3973 jsr166 1.121 long startTime = System.nanoTime();
3974 jsr166 1.145 assertSame(f, f.completeOnTimeout(v, timeoutMillis, MILLISECONDS));
3975 jsr166 1.121 assertSame(v, f.join());
3976     assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
3977     f.complete(99); // should have no effect
3978     checkCompletedNormally(f, v);
3979 dl 1.103 }
3980    
3981     /**
3982 jsr166 1.106 * completeOnTimeout has no effect if completed within timeout
3983 dl 1.103 */
3984 jsr166 1.121 public void testCompleteOnTimeout_completed() {
3985     for (Integer v1 : new Integer[] { 1, null })
3986     {
3987 dl 1.103 CompletableFuture<Integer> f = new CompletableFuture<>();
3988 jsr166 1.121 CompletableFuture<Integer> g = new CompletableFuture<>();
3989     long startTime = System.nanoTime();
3990     f.complete(v1);
3991 jsr166 1.145 assertSame(f, f.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3992     assertSame(g, g.completeOnTimeout(-1, LONG_DELAY_MS, MILLISECONDS));
3993 jsr166 1.121 g.complete(v1);
3994     checkCompletedNormally(f, v1);
3995     checkCompletedNormally(g, v1);
3996     assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS / 2);
3997     }}
3998 dl 1.103
3999     /**
4000     * delayedExecutor returns an executor that delays submission
4001     */
4002 jsr166 1.121 public void testDelayedExecutor() {
4003     testInParallel(() -> testDelayedExecutor(null, null),
4004     () -> testDelayedExecutor(null, 1),
4005     () -> testDelayedExecutor(new ThreadExecutor(), 1),
4006     () -> testDelayedExecutor(new ThreadExecutor(), 1));
4007 dl 1.103 }
4008    
4009 jsr166 1.121 public void testDelayedExecutor(Executor executor, Integer v) throws Exception {
4010     long timeoutMillis = timeoutMillis();
4011     // Use an "unreasonably long" long timeout to catch lingering threads
4012     long longTimeoutMillis = 1000 * 60 * 60 * 24;
4013     final Executor delayer, longDelayer;
4014     if (executor == null) {
4015     delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS);
4016     longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS);
4017     } else {
4018     delayer = CompletableFuture.delayedExecutor(timeoutMillis, MILLISECONDS, executor);
4019     longDelayer = CompletableFuture.delayedExecutor(longTimeoutMillis, MILLISECONDS, executor);
4020     }
4021 dl 1.103 long startTime = System.nanoTime();
4022 jsr166 1.121 CompletableFuture<Integer> f =
4023     CompletableFuture.supplyAsync(() -> v, delayer);
4024     CompletableFuture<Integer> g =
4025     CompletableFuture.supplyAsync(() -> v, longDelayer);
4026    
4027     assertNull(g.getNow(null));
4028    
4029     assertSame(v, f.get(LONG_DELAY_MS, MILLISECONDS));
4030     long millisElapsed = millisElapsedSince(startTime);
4031     assertTrue(millisElapsed >= timeoutMillis);
4032     assertTrue(millisElapsed < LONG_DELAY_MS / 2);
4033    
4034     checkCompletedNormally(f, v);
4035    
4036     checkIncomplete(g);
4037     assertTrue(g.cancel(true));
4038 dl 1.103 }
4039    
4040 jsr166 1.82 //--- tests of implementation details; not part of official tck ---
4041    
4042     Object resultOf(CompletableFuture<?> f) {
4043 jsr166 1.147 SecurityManager sm = System.getSecurityManager();
4044     if (sm != null) {
4045     try {
4046     System.setSecurityManager(null);
4047     } catch (SecurityException giveUp) {
4048     return "Reflection not available";
4049     }
4050     }
4051    
4052 jsr166 1.82 try {
4053     java.lang.reflect.Field resultField
4054     = CompletableFuture.class.getDeclaredField("result");
4055     resultField.setAccessible(true);
4056     return resultField.get(f);
4057 jsr166 1.147 } catch (Throwable t) {
4058     throw new AssertionError(t);
4059     } finally {
4060     if (sm != null) System.setSecurityManager(sm);
4061     }
4062 jsr166 1.82 }
4063    
4064     public void testExceptionPropagationReusesResultObject() {
4065     if (!testImplementationDetails) return;
4066     for (ExecutionMode m : ExecutionMode.values())
4067     {
4068 jsr166 1.83 final CFException ex = new CFException();
4069     final CompletableFuture<Integer> v42 = CompletableFuture.completedFuture(42);
4070     final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
4071    
4072 jsr166 1.164 final Runnable noopRunnable = new Noop(m);
4073     final Consumer<Integer> noopConsumer = new NoopConsumer(m);
4074     final Function<Integer, Integer> incFunction = new IncFunction(m);
4075    
4076 jsr166 1.89 List<Function<CompletableFuture<Integer>, CompletableFuture<?>>> funs
4077 jsr166 1.83 = new ArrayList<>();
4078    
4079 jsr166 1.180 funs.add(y -> m.thenRun(y, noopRunnable));
4080     funs.add(y -> m.thenAccept(y, noopConsumer));
4081     funs.add(y -> m.thenApply(y, incFunction));
4082    
4083     funs.add(y -> m.runAfterEither(y, incomplete, noopRunnable));
4084     funs.add(y -> m.acceptEither(y, incomplete, noopConsumer));
4085     funs.add(y -> m.applyToEither(y, incomplete, incFunction));
4086    
4087     funs.add(y -> m.runAfterBoth(y, v42, noopRunnable));
4088     funs.add(y -> m.runAfterBoth(v42, y, noopRunnable));
4089     funs.add(y -> m.thenAcceptBoth(y, v42, new SubtractAction(m)));
4090     funs.add(y -> m.thenAcceptBoth(v42, y, new SubtractAction(m)));
4091     funs.add(y -> m.thenCombine(y, v42, new SubtractFunction(m)));
4092     funs.add(y -> m.thenCombine(v42, y, new SubtractFunction(m)));
4093    
4094     funs.add(y -> m.whenComplete(y, (Integer r, Throwable t) -> {}));
4095    
4096     funs.add(y -> m.thenCompose(y, new CompletableFutureInc(m)));
4097    
4098     funs.add(y -> CompletableFuture.allOf(y));
4099     funs.add(y -> CompletableFuture.allOf(y, v42));
4100     funs.add(y -> CompletableFuture.allOf(v42, y));
4101     funs.add(y -> CompletableFuture.anyOf(y));
4102     funs.add(y -> CompletableFuture.anyOf(y, incomplete));
4103     funs.add(y -> CompletableFuture.anyOf(incomplete, y));
4104 jsr166 1.85
4105 jsr166 1.83 for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
4106 jsr166 1.89 fun : funs) {
4107 jsr166 1.83 CompletableFuture<Integer> f = new CompletableFuture<>();
4108     f.completeExceptionally(ex);
4109 jsr166 1.164 CompletableFuture<Integer> src = m.thenApply(f, incFunction);
4110 jsr166 1.83 checkCompletedWithWrappedException(src, ex);
4111 jsr166 1.89 CompletableFuture<?> dep = fun.apply(src);
4112 jsr166 1.83 checkCompletedWithWrappedException(dep, ex);
4113     assertSame(resultOf(src), resultOf(dep));
4114     }
4115    
4116     for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
4117 jsr166 1.89 fun : funs) {
4118 jsr166 1.83 CompletableFuture<Integer> f = new CompletableFuture<>();
4119 jsr166 1.164 CompletableFuture<Integer> src = m.thenApply(f, incFunction);
4120 jsr166 1.89 CompletableFuture<?> dep = fun.apply(src);
4121 jsr166 1.83 f.completeExceptionally(ex);
4122     checkCompletedWithWrappedException(src, ex);
4123     checkCompletedWithWrappedException(dep, ex);
4124     assertSame(resultOf(src), resultOf(dep));
4125     }
4126    
4127     for (boolean mayInterruptIfRunning : new boolean[] { true, false })
4128     for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
4129 jsr166 1.89 fun : funs) {
4130 jsr166 1.83 CompletableFuture<Integer> f = new CompletableFuture<>();
4131     f.cancel(mayInterruptIfRunning);
4132     checkCancelled(f);
4133 jsr166 1.164 CompletableFuture<Integer> src = m.thenApply(f, incFunction);
4134 jsr166 1.83 checkCompletedWithWrappedCancellationException(src);
4135 jsr166 1.89 CompletableFuture<?> dep = fun.apply(src);
4136 jsr166 1.83 checkCompletedWithWrappedCancellationException(dep);
4137     assertSame(resultOf(src), resultOf(dep));
4138     }
4139    
4140     for (boolean mayInterruptIfRunning : new boolean[] { true, false })
4141     for (Function<CompletableFuture<Integer>, CompletableFuture<?>>
4142 jsr166 1.89 fun : funs) {
4143 jsr166 1.83 CompletableFuture<Integer> f = new CompletableFuture<>();
4144 jsr166 1.164 CompletableFuture<Integer> src = m.thenApply(f, incFunction);
4145 jsr166 1.89 CompletableFuture<?> dep = fun.apply(src);
4146 jsr166 1.83 f.cancel(mayInterruptIfRunning);
4147     checkCancelled(f);
4148     checkCompletedWithWrappedCancellationException(src);
4149     checkCompletedWithWrappedCancellationException(dep);
4150     assertSame(resultOf(src), resultOf(dep));
4151     }
4152 jsr166 1.82 }}
4153    
4154 jsr166 1.123 /**
4155 jsr166 1.165 * Minimal completion stages throw UOE for most non-CompletionStage methods
4156 jsr166 1.123 */
4157     public void testMinimalCompletionStage_minimality() {
4158     if (!testImplementationDetails) return;
4159     Function<Method, String> toSignature =
4160 jsr166 1.180 method -> method.getName() + Arrays.toString(method.getParameterTypes());
4161 jsr166 1.124 Predicate<Method> isNotStatic =
4162 jsr166 1.180 method -> (method.getModifiers() & Modifier.STATIC) == 0;
4163 jsr166 1.123 List<Method> minimalMethods =
4164     Stream.of(Object.class, CompletionStage.class)
4165 jsr166 1.180 .flatMap(klazz -> Stream.of(klazz.getMethods()))
4166 jsr166 1.124 .filter(isNotStatic)
4167 jsr166 1.123 .collect(Collectors.toList());
4168     // Methods from CompletableFuture permitted NOT to throw UOE
4169     String[] signatureWhitelist = {
4170     "newIncompleteFuture[]",
4171     "defaultExecutor[]",
4172     "minimalCompletionStage[]",
4173     "copy[]",
4174     };
4175     Set<String> permittedMethodSignatures =
4176     Stream.concat(minimalMethods.stream().map(toSignature),
4177     Stream.of(signatureWhitelist))
4178     .collect(Collectors.toSet());
4179     List<Method> allMethods = Stream.of(CompletableFuture.class.getMethods())
4180 jsr166 1.124 .filter(isNotStatic)
4181 jsr166 1.180 .filter(method -> !permittedMethodSignatures.contains(toSignature.apply(method)))
4182 jsr166 1.123 .collect(Collectors.toList());
4183    
4184 jsr166 1.165 List<CompletionStage<Integer>> stages = new ArrayList<>();
4185 jsr166 1.173 CompletionStage<Integer> min =
4186     new CompletableFuture<Integer>().minimalCompletionStage();
4187     stages.add(min);
4188     stages.add(min.thenApply(x -> x));
4189 jsr166 1.165 stages.add(CompletableFuture.completedStage(1));
4190 jsr166 1.166 stages.add(CompletableFuture.failedStage(new CFException()));
4191 jsr166 1.123
4192     List<Method> bugs = new ArrayList<>();
4193     for (Method method : allMethods) {
4194     Class<?>[] parameterTypes = method.getParameterTypes();
4195     Object[] args = new Object[parameterTypes.length];
4196     // Manufacture boxed primitives for primitive params
4197     for (int i = 0; i < args.length; i++) {
4198     Class<?> type = parameterTypes[i];
4199     if (parameterTypes[i] == boolean.class)
4200     args[i] = false;
4201     else if (parameterTypes[i] == int.class)
4202     args[i] = 0;
4203     else if (parameterTypes[i] == long.class)
4204     args[i] = 0L;
4205     }
4206 jsr166 1.165 for (CompletionStage<Integer> stage : stages) {
4207     try {
4208     method.invoke(stage, args);
4209 jsr166 1.123 bugs.add(method);
4210     }
4211 jsr166 1.165 catch (java.lang.reflect.InvocationTargetException expected) {
4212     if (! (expected.getCause() instanceof UnsupportedOperationException)) {
4213     bugs.add(method);
4214     // expected.getCause().printStackTrace();
4215     }
4216     }
4217     catch (ReflectiveOperationException bad) { throw new Error(bad); }
4218 jsr166 1.123 }
4219     }
4220     if (!bugs.isEmpty())
4221 jsr166 1.165 throw new Error("Methods did not throw UOE: " + bugs);
4222 jsr166 1.123 }
4223    
4224 jsr166 1.173 /**
4225 jsr166 1.176 * minimalStage.toCompletableFuture() returns a CompletableFuture that
4226     * is completed normally, with the same value, when source is.
4227     */
4228     public void testMinimalCompletionStage_toCompletableFuture_normalCompletion() {
4229     for (boolean createIncomplete : new boolean[] { true, false })
4230     for (Integer v1 : new Integer[] { 1, null })
4231     {
4232     CompletableFuture<Integer> f = new CompletableFuture<>();
4233     CompletionStage<Integer> minimal = f.minimalCompletionStage();
4234     if (!createIncomplete) assertTrue(f.complete(v1));
4235     CompletableFuture<Integer> g = minimal.toCompletableFuture();
4236     if (createIncomplete) {
4237     checkIncomplete(f);
4238     checkIncomplete(g);
4239     assertTrue(f.complete(v1));
4240     }
4241     checkCompletedNormally(f, v1);
4242     checkCompletedNormally(g, v1);
4243     }}
4244    
4245     /**
4246 jsr166 1.177 * minimalStage.toCompletableFuture() returns a CompletableFuture that
4247     * is completed exceptionally when source is.
4248     */
4249     public void testMinimalCompletionStage_toCompletableFuture_exceptionalCompletion() {
4250     for (boolean createIncomplete : new boolean[] { true, false })
4251     {
4252     CFException ex = new CFException();
4253     CompletableFuture<Integer> f = new CompletableFuture<>();
4254     CompletionStage<Integer> minimal = f.minimalCompletionStage();
4255     if (!createIncomplete) f.completeExceptionally(ex);
4256     CompletableFuture<Integer> g = minimal.toCompletableFuture();
4257     if (createIncomplete) {
4258     checkIncomplete(f);
4259     checkIncomplete(g);
4260     f.completeExceptionally(ex);
4261     }
4262     checkCompletedExceptionally(f, ex);
4263     checkCompletedWithWrappedException(g, ex);
4264     }}
4265    
4266     /**
4267 jsr166 1.173 * minimalStage.toCompletableFuture() gives mutable CompletableFuture
4268     */
4269     public void testMinimalCompletionStage_toCompletableFuture_mutable() {
4270     for (Integer v1 : new Integer[] { 1, null })
4271     {
4272     CompletableFuture<Integer> f = new CompletableFuture<>();
4273     CompletionStage minimal = f.minimalCompletionStage();
4274     CompletableFuture<Integer> g = minimal.toCompletableFuture();
4275 jsr166 1.178 assertTrue(g.complete(v1));
4276 jsr166 1.173 checkCompletedNormally(g, v1);
4277     checkIncomplete(f);
4278     checkIncomplete(minimal.toCompletableFuture());
4279     }}
4280    
4281     /**
4282     * minimalStage.toCompletableFuture().join() awaits completion
4283     */
4284     public void testMinimalCompletionStage_toCompletableFuture_join() throws Exception {
4285     for (boolean createIncomplete : new boolean[] { true, false })
4286     for (Integer v1 : new Integer[] { 1, null })
4287     {
4288     CompletableFuture<Integer> f = new CompletableFuture<>();
4289     if (!createIncomplete) assertTrue(f.complete(v1));
4290     CompletionStage<Integer> minimal = f.minimalCompletionStage();
4291     if (createIncomplete) assertTrue(f.complete(v1));
4292     assertEquals(v1, minimal.toCompletableFuture().join());
4293     assertEquals(v1, minimal.toCompletableFuture().get());
4294     checkCompletedNormally(minimal.toCompletableFuture(), v1);
4295     }}
4296    
4297 jsr166 1.175 /**
4298     * Completion of a toCompletableFuture copy of a minimal stage
4299     * does not complete its source.
4300     */
4301     public void testMinimalCompletionStage_toCompletableFuture_oneWayPropagation() {
4302     CompletableFuture<Integer> f = new CompletableFuture<>();
4303     CompletionStage<Integer> g = f.minimalCompletionStage();
4304     assertTrue(g.toCompletableFuture().complete(1));
4305     assertTrue(g.toCompletableFuture().complete(null));
4306     assertTrue(g.toCompletableFuture().cancel(true));
4307     assertTrue(g.toCompletableFuture().cancel(false));
4308     assertTrue(g.toCompletableFuture().completeExceptionally(new CFException()));
4309     checkIncomplete(g.toCompletableFuture());
4310     f.complete(1);
4311     checkCompletedNormally(g.toCompletableFuture(), 1);
4312     }
4313    
4314 jsr166 1.173 /** Demo utility method for external reliable toCompletableFuture */
4315     static <T> CompletableFuture<T> toCompletableFuture(CompletionStage<T> stage) {
4316     CompletableFuture<T> f = new CompletableFuture<>();
4317     stage.handle((T t, Throwable ex) -> {
4318     if (ex != null) f.completeExceptionally(ex);
4319     else f.complete(t);
4320     return null;
4321     });
4322     return f;
4323     }
4324    
4325     /** Demo utility method to join a CompletionStage */
4326     static <T> T join(CompletionStage<T> stage) {
4327     return toCompletableFuture(stage).join();
4328     }
4329    
4330     /**
4331     * Joining a minimal stage "by hand" works
4332     */
4333     public void testMinimalCompletionStage_join_by_hand() {
4334     for (boolean createIncomplete : new boolean[] { true, false })
4335     for (Integer v1 : new Integer[] { 1, null })
4336     {
4337     CompletableFuture<Integer> f = new CompletableFuture<>();
4338     CompletionStage<Integer> minimal = f.minimalCompletionStage();
4339     CompletableFuture<Integer> g = new CompletableFuture<>();
4340     if (!createIncomplete) assertTrue(f.complete(v1));
4341 jsr166 1.180 minimal.thenAccept(x -> g.complete(x));
4342 jsr166 1.173 if (createIncomplete) assertTrue(f.complete(v1));
4343     g.join();
4344     checkCompletedNormally(g, v1);
4345     checkCompletedNormally(f, v1);
4346     assertEquals(v1, join(minimal));
4347     }}
4348    
4349 jsr166 1.128 static class Monad {
4350 jsr166 1.131 static class ZeroException extends RuntimeException {
4351     public ZeroException() { super("monadic zero"); }
4352 jsr166 1.128 }
4353     // "return", "unit"
4354     static <T> CompletableFuture<T> unit(T value) {
4355     return completedFuture(value);
4356     }
4357     // monadic zero ?
4358 jsr166 1.129 static <T> CompletableFuture<T> zero() {
4359 jsr166 1.131 return failedFuture(new ZeroException());
4360 jsr166 1.128 }
4361     // >=>
4362     static <T,U,V> Function<T, CompletableFuture<V>> compose
4363     (Function<T, CompletableFuture<U>> f,
4364     Function<U, CompletableFuture<V>> g) {
4365 jsr166 1.180 return x -> f.apply(x).thenCompose(g);
4366 jsr166 1.128 }
4367    
4368     static void assertZero(CompletableFuture<?> f) {
4369     try {
4370     f.getNow(null);
4371 jsr166 1.192 throw new AssertionError("should throw");
4372 jsr166 1.128 } catch (CompletionException success) {
4373 jsr166 1.131 assertTrue(success.getCause() instanceof ZeroException);
4374 jsr166 1.128 }
4375     }
4376    
4377     static <T> void assertFutureEquals(CompletableFuture<T> f,
4378     CompletableFuture<T> g) {
4379     T fval = null, gval = null;
4380     Throwable fex = null, gex = null;
4381    
4382     try { fval = f.get(); }
4383     catch (ExecutionException ex) { fex = ex.getCause(); }
4384     catch (Throwable ex) { fex = ex; }
4385    
4386     try { gval = g.get(); }
4387     catch (ExecutionException ex) { gex = ex.getCause(); }
4388     catch (Throwable ex) { gex = ex; }
4389    
4390     if (fex != null || gex != null)
4391     assertSame(fex.getClass(), gex.getClass());
4392     else
4393     assertEquals(fval, gval);
4394     }
4395    
4396     static class PlusFuture<T> extends CompletableFuture<T> {
4397     AtomicReference<Throwable> firstFailure = new AtomicReference<>(null);
4398     }
4399    
4400 jsr166 1.137 /** Implements "monadic plus". */
4401 jsr166 1.128 static <T> CompletableFuture<T> plus(CompletableFuture<? extends T> f,
4402     CompletableFuture<? extends T> g) {
4403     PlusFuture<T> plus = new PlusFuture<T>();
4404 jsr166 1.129 BiConsumer<T, Throwable> action = (T result, Throwable ex) -> {
4405 jsr166 1.137 try {
4406     if (ex == null) {
4407     if (plus.complete(result))
4408     if (plus.firstFailure.get() != null)
4409     plus.firstFailure.set(null);
4410     }
4411     else if (plus.firstFailure.compareAndSet(null, ex)) {
4412     if (plus.isDone())
4413 jsr166 1.128 plus.firstFailure.set(null);
4414 jsr166 1.137 }
4415     else {
4416     // first failure has precedence
4417     Throwable first = plus.firstFailure.getAndSet(null);
4418    
4419     // may fail with "Self-suppression not permitted"
4420     try { first.addSuppressed(ex); }
4421     catch (Exception ignored) {}
4422    
4423     plus.completeExceptionally(first);
4424     }
4425     } catch (Throwable unexpected) {
4426     plus.completeExceptionally(unexpected);
4427 jsr166 1.128 }
4428     };
4429     f.whenComplete(action);
4430     g.whenComplete(action);
4431     return plus;
4432     }
4433     }
4434    
4435     /**
4436     * CompletableFuture is an additive monad - sort of.
4437     * https://en.wikipedia.org/wiki/Monad_(functional_programming)#Additive_monads
4438     */
4439     public void testAdditiveMonad() throws Throwable {
4440 jsr166 1.129 Function<Long, CompletableFuture<Long>> unit = Monad::unit;
4441     CompletableFuture<Long> zero = Monad.zero();
4442    
4443 jsr166 1.128 // Some mutually non-commutative functions
4444     Function<Long, CompletableFuture<Long>> triple
4445 jsr166 1.180 = x -> Monad.unit(3 * x);
4446 jsr166 1.128 Function<Long, CompletableFuture<Long>> inc
4447 jsr166 1.180 = x -> Monad.unit(x + 1);
4448 jsr166 1.128
4449     // unit is a right identity: m >>= unit === m
4450 jsr166 1.129 Monad.assertFutureEquals(inc.apply(5L).thenCompose(unit),
4451     inc.apply(5L));
4452 jsr166 1.128 // unit is a left identity: (unit x) >>= f === f x
4453 jsr166 1.129 Monad.assertFutureEquals(unit.apply(5L).thenCompose(inc),
4454     inc.apply(5L));
4455    
4456 jsr166 1.128 // associativity: (m >>= f) >>= g === m >>= ( \x -> (f x >>= g) )
4457     Monad.assertFutureEquals(
4458     unit.apply(5L).thenCompose(inc).thenCompose(triple),
4459 jsr166 1.180 unit.apply(5L).thenCompose(x -> inc.apply(x).thenCompose(triple)));
4460 jsr166 1.128
4461 jsr166 1.129 // The case for CompletableFuture as an additive monad is weaker...
4462    
4463 jsr166 1.128 // zero is a monadic zero
4464 jsr166 1.129 Monad.assertZero(zero);
4465    
4466 jsr166 1.128 // left zero: zero >>= f === zero
4467 jsr166 1.129 Monad.assertZero(zero.thenCompose(inc));
4468     // right zero: f >>= (\x -> zero) === zero
4469 jsr166 1.180 Monad.assertZero(inc.apply(5L).thenCompose(x -> zero));
4470 jsr166 1.129
4471     // f plus zero === f
4472     Monad.assertFutureEquals(Monad.unit(5L),
4473     Monad.plus(Monad.unit(5L), zero));
4474     // zero plus f === f
4475     Monad.assertFutureEquals(Monad.unit(5L),
4476     Monad.plus(zero, Monad.unit(5L)));
4477 jsr166 1.128 // zero plus zero === zero
4478 jsr166 1.129 Monad.assertZero(Monad.plus(zero, zero));
4479 jsr166 1.128 {
4480 jsr166 1.129 CompletableFuture<Long> f = Monad.plus(Monad.unit(5L),
4481     Monad.unit(8L));
4482     // non-determinism
4483     assertTrue(f.get() == 5L || f.get() == 8L);
4484 jsr166 1.128 }
4485    
4486     CompletableFuture<Long> godot = new CompletableFuture<>();
4487 jsr166 1.129 // f plus godot === f (doesn't wait for godot)
4488     Monad.assertFutureEquals(Monad.unit(5L),
4489     Monad.plus(Monad.unit(5L), godot));
4490     // godot plus f === f (doesn't wait for godot)
4491     Monad.assertFutureEquals(Monad.unit(5L),
4492     Monad.plus(godot, Monad.unit(5L)));
4493 jsr166 1.128 }
4494    
4495 jsr166 1.163 /** Test long recursive chains of CompletableFutures with cascading completions */
4496 jsr166 1.187 @SuppressWarnings("FutureReturnValueIgnored")
4497 jsr166 1.163 public void testRecursiveChains() throws Throwable {
4498     for (ExecutionMode m : ExecutionMode.values())
4499     for (boolean addDeadEnds : new boolean[] { true, false })
4500     {
4501     final int val = 42;
4502     final int n = expensiveTests ? 1_000 : 2;
4503     CompletableFuture<Integer> head = new CompletableFuture<>();
4504     CompletableFuture<Integer> tail = head;
4505     for (int i = 0; i < n; i++) {
4506     if (addDeadEnds) m.thenApply(tail, v -> v + 1);
4507     tail = m.thenApply(tail, v -> v + 1);
4508     if (addDeadEnds) m.applyToEither(tail, tail, v -> v + 1);
4509     tail = m.applyToEither(tail, tail, v -> v + 1);
4510     if (addDeadEnds) m.thenCombine(tail, tail, (v, w) -> v + 1);
4511     tail = m.thenCombine(tail, tail, (v, w) -> v + 1);
4512     }
4513     head.complete(val);
4514     assertEquals(val + 3 * n, (int) tail.join());
4515     }}
4516    
4517 jsr166 1.140 /**
4518     * A single CompletableFuture with many dependents.
4519 jsr166 1.141 * A demo of scalability - runtime is O(n).
4520 jsr166 1.140 */
4521 jsr166 1.187 @SuppressWarnings("FutureReturnValueIgnored")
4522 jsr166 1.140 public void testManyDependents() throws Throwable {
4523 jsr166 1.159 final int n = expensiveTests ? 1_000_000 : 10;
4524 jsr166 1.140 final CompletableFuture<Void> head = new CompletableFuture<>();
4525     final CompletableFuture<Void> complete = CompletableFuture.completedFuture((Void)null);
4526     final AtomicInteger count = new AtomicInteger(0);
4527     for (int i = 0; i < n; i++) {
4528     head.thenRun(() -> count.getAndIncrement());
4529 jsr166 1.180 head.thenAccept(x -> count.getAndIncrement());
4530     head.thenApply(x -> count.getAndIncrement());
4531 jsr166 1.141
4532 jsr166 1.140 head.runAfterBoth(complete, () -> count.getAndIncrement());
4533     head.thenAcceptBoth(complete, (x, y) -> count.getAndIncrement());
4534     head.thenCombine(complete, (x, y) -> count.getAndIncrement());
4535 jsr166 1.141 complete.runAfterBoth(head, () -> count.getAndIncrement());
4536     complete.thenAcceptBoth(head, (x, y) -> count.getAndIncrement());
4537     complete.thenCombine(head, (x, y) -> count.getAndIncrement());
4538    
4539     head.runAfterEither(new CompletableFuture<Void>(), () -> count.getAndIncrement());
4540 jsr166 1.180 head.acceptEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4541     head.applyToEither(new CompletableFuture<Void>(), x -> count.getAndIncrement());
4542 jsr166 1.141 new CompletableFuture<Void>().runAfterEither(head, () -> count.getAndIncrement());
4543 jsr166 1.180 new CompletableFuture<Void>().acceptEither(head, x -> count.getAndIncrement());
4544     new CompletableFuture<Void>().applyToEither(head, x -> count.getAndIncrement());
4545 jsr166 1.140 }
4546     head.complete(null);
4547 jsr166 1.141 assertEquals(5 * 3 * n, count.get());
4548 jsr166 1.140 }
4549    
4550 jsr166 1.160 /** ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest tck */
4551 jsr166 1.187 @SuppressWarnings("FutureReturnValueIgnored")
4552 jsr166 1.160 public void testCoCompletionGarbageRetention() throws Throwable {
4553 jsr166 1.159 final int n = expensiveTests ? 1_000_000 : 10;
4554 jsr166 1.156 final CompletableFuture<Integer> incomplete = new CompletableFuture<>();
4555     CompletableFuture<Integer> f;
4556     for (int i = 0; i < n; i++) {
4557     f = new CompletableFuture<>();
4558     f.runAfterEither(incomplete, () -> {});
4559     f.complete(null);
4560    
4561     f = new CompletableFuture<>();
4562 jsr166 1.180 f.acceptEither(incomplete, x -> {});
4563 jsr166 1.156 f.complete(null);
4564    
4565     f = new CompletableFuture<>();
4566 jsr166 1.180 f.applyToEither(incomplete, x -> x);
4567 jsr166 1.156 f.complete(null);
4568    
4569     f = new CompletableFuture<>();
4570 jsr166 1.194 CompletableFuture.anyOf(f, incomplete);
4571 jsr166 1.156 f.complete(null);
4572     }
4573    
4574     for (int i = 0; i < n; i++) {
4575     f = new CompletableFuture<>();
4576     incomplete.runAfterEither(f, () -> {});
4577     f.complete(null);
4578    
4579     f = new CompletableFuture<>();
4580 jsr166 1.180 incomplete.acceptEither(f, x -> {});
4581 jsr166 1.156 f.complete(null);
4582    
4583     f = new CompletableFuture<>();
4584 jsr166 1.180 incomplete.applyToEither(f, x -> x);
4585 jsr166 1.156 f.complete(null);
4586    
4587     f = new CompletableFuture<>();
4588 jsr166 1.194 CompletableFuture.anyOf(incomplete, f);
4589 jsr166 1.156 f.complete(null);
4590     }
4591     }
4592    
4593 jsr166 1.167 /**
4594 jsr166 1.170 * Reproduction recipe for:
4595     * 8160402: Garbage retention with CompletableFuture.anyOf
4596     * cvs update -D '2016-05-01' ./src/main/java/util/concurrent/CompletableFuture.java && ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testAnyOfGarbageRetention tck; cvs update -A
4597 jsr166 1.158 */
4598     public void testAnyOfGarbageRetention() throws Throwable {
4599     for (Integer v : new Integer[] { 1, null })
4600     {
4601     final int n = expensiveTests ? 100_000 : 10;
4602     CompletableFuture<Integer>[] fs
4603     = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4604     for (int i = 0; i < fs.length; i++)
4605     fs[i] = new CompletableFuture<>();
4606     fs[fs.length - 1].complete(v);
4607     for (int i = 0; i < n; i++)
4608     checkCompletedNormally(CompletableFuture.anyOf(fs), v);
4609     }}
4610    
4611 jsr166 1.167 /**
4612     * Checks for garbage retention with allOf.
4613     *
4614     * As of 2016-07, fails with OOME:
4615     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledAllOfGarbageRetention tck
4616     */
4617 jsr166 1.158 public void testCancelledAllOfGarbageRetention() throws Throwable {
4618     final int n = expensiveTests ? 100_000 : 10;
4619     CompletableFuture<Integer>[] fs
4620     = (CompletableFuture<Integer>[]) new CompletableFuture<?>[100];
4621     for (int i = 0; i < fs.length; i++)
4622     fs[i] = new CompletableFuture<>();
4623     for (int i = 0; i < n; i++)
4624     assertTrue(CompletableFuture.allOf(fs).cancel(false));
4625     }
4626    
4627 jsr166 1.168 /**
4628     * Checks for garbage retention when a dependent future is
4629     * cancelled and garbage-collected.
4630 jsr166 1.169 * 8161600: Garbage retention when source CompletableFutures are never completed
4631 jsr166 1.168 *
4632     * As of 2016-07, fails with OOME:
4633     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledGarbageRetention tck
4634     */
4635     public void testCancelledGarbageRetention() throws Throwable {
4636     final int n = expensiveTests ? 100_000 : 10;
4637     CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4638     for (int i = 0; i < n; i++)
4639     assertTrue(neverCompleted.thenRun(() -> {}).cancel(true));
4640     }
4641    
4642 jsr166 1.179 /**
4643     * Checks for garbage retention when MinimalStage.toCompletableFuture()
4644     * is invoked many times.
4645     * 8161600: Garbage retention when source CompletableFutures are never completed
4646     *
4647     * As of 2016-07, fails with OOME:
4648     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testToCompletableFutureGarbageRetention tck
4649     */
4650     public void testToCompletableFutureGarbageRetention() throws Throwable {
4651     final int n = expensiveTests ? 900_000 : 10;
4652     CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
4653     CompletionStage minimal = neverCompleted.minimalCompletionStage();
4654     for (int i = 0; i < n; i++)
4655     assertTrue(minimal.toCompletableFuture().cancel(true));
4656     }
4657    
4658 jsr166 1.123 // static <U> U join(CompletionStage<U> stage) {
4659     // CompletableFuture<U> f = new CompletableFuture<>();
4660     // stage.whenComplete((v, ex) -> {
4661     // if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4662     // });
4663     // return f.join();
4664     // }
4665    
4666     // static <U> boolean isDone(CompletionStage<U> stage) {
4667     // CompletableFuture<U> f = new CompletableFuture<>();
4668     // stage.whenComplete((v, ex) -> {
4669     // if (ex != null) f.completeExceptionally(ex); else f.complete(v);
4670     // });
4671     // return f.isDone();
4672     // }
4673    
4674     // static <U> U join2(CompletionStage<U> stage) {
4675     // return stage.toCompletableFuture().copy().join();
4676     // }
4677    
4678     // static <U> boolean isDone2(CompletionStage<U> stage) {
4679     // return stage.toCompletableFuture().copy().isDone();
4680     // }
4681    
4682 dl 1.199 // For testing default implementations
4683     // Only non-default interface methods defined.
4684     static final class DelegatedCompletionStage<T> implements CompletionStage<T> {
4685     final CompletableFuture<T> cf;
4686     DelegatedCompletionStage(CompletableFuture<T> cf) { this.cf = cf; }
4687     public CompletableFuture<T> toCompletableFuture() {
4688     return cf; }
4689     public CompletionStage<Void> thenRun
4690     (Runnable action) {
4691     return cf.thenRun(action); }
4692     public CompletionStage<Void> thenRunAsync
4693     (Runnable action) {
4694     return cf.thenRunAsync(action); }
4695     public CompletionStage<Void> thenRunAsync
4696     (Runnable action,
4697     Executor executor) {
4698     return cf.thenRunAsync(action, executor); }
4699     public CompletionStage<Void> thenAccept
4700     (Consumer<? super T> action) {
4701     return cf.thenAccept(action); }
4702     public CompletionStage<Void> thenAcceptAsync
4703     (Consumer<? super T> action) {
4704     return cf.thenAcceptAsync(action); }
4705     public CompletionStage<Void> thenAcceptAsync
4706     (Consumer<? super T> action,
4707     Executor executor) {
4708     return cf.thenAcceptAsync(action, executor); }
4709     public <U> CompletionStage<U> thenApply
4710     (Function<? super T,? extends U> a) {
4711     return cf.thenApply(a); }
4712     public <U> CompletionStage<U> thenApplyAsync
4713     (Function<? super T,? extends U> fn) {
4714     return cf.thenApplyAsync(fn); }
4715     public <U> CompletionStage<U> thenApplyAsync
4716     (Function<? super T,? extends U> fn,
4717     Executor executor) {
4718     return cf.thenApplyAsync(fn, executor); }
4719     public <U,V> CompletionStage<V> thenCombine
4720     (CompletionStage<? extends U> other,
4721     BiFunction<? super T,? super U,? extends V> fn) {
4722     return cf.thenCombine(other, fn); }
4723     public <U,V> CompletionStage<V> thenCombineAsync
4724     (CompletionStage<? extends U> other,
4725     BiFunction<? super T,? super U,? extends V> fn) {
4726     return cf.thenCombineAsync(other, fn); }
4727     public <U,V> CompletionStage<V> thenCombineAsync
4728     (CompletionStage<? extends U> other,
4729     BiFunction<? super T,? super U,? extends V> fn,
4730     Executor executor) {
4731     return cf.thenCombineAsync(other, fn, executor); }
4732     public <U> CompletionStage<Void> thenAcceptBoth
4733     (CompletionStage<? extends U> other,
4734     BiConsumer<? super T, ? super U> action) {
4735     return cf.thenAcceptBoth(other, action); }
4736     public <U> CompletionStage<Void> thenAcceptBothAsync
4737     (CompletionStage<? extends U> other,
4738     BiConsumer<? super T, ? super U> action) {
4739     return cf.thenAcceptBothAsync(other, action); }
4740     public <U> CompletionStage<Void> thenAcceptBothAsync
4741     (CompletionStage<? extends U> other,
4742     BiConsumer<? super T, ? super U> action,
4743     Executor executor) {
4744     return cf.thenAcceptBothAsync(other, action, executor); }
4745     public CompletionStage<Void> runAfterBoth
4746     (CompletionStage<?> other,
4747     Runnable action) {
4748     return cf.runAfterBoth(other, action); }
4749     public CompletionStage<Void> runAfterBothAsync
4750     (CompletionStage<?> other,
4751     Runnable action) {
4752     return cf.runAfterBothAsync(other, action); }
4753     public CompletionStage<Void> runAfterBothAsync
4754     (CompletionStage<?> other,
4755     Runnable action,
4756     Executor executor) {
4757     return cf.runAfterBothAsync(other, action, executor); }
4758     public <U> CompletionStage<U> applyToEither
4759     (CompletionStage<? extends T> other,
4760     Function<? super T, U> fn) {
4761     return cf.applyToEither(other, fn); }
4762     public <U> CompletionStage<U> applyToEitherAsync
4763     (CompletionStage<? extends T> other,
4764     Function<? super T, U> fn) {
4765     return cf.applyToEitherAsync(other, fn); }
4766     public <U> CompletionStage<U> applyToEitherAsync
4767     (CompletionStage<? extends T> other,
4768     Function<? super T, U> fn,
4769     Executor executor) {
4770     return cf.applyToEitherAsync(other, fn, executor); }
4771     public CompletionStage<Void> acceptEither
4772     (CompletionStage<? extends T> other,
4773     Consumer<? super T> action) {
4774     return cf.acceptEither(other, action); }
4775     public CompletionStage<Void> acceptEitherAsync
4776     (CompletionStage<? extends T> other,
4777     Consumer<? super T> action) {
4778     return cf.acceptEitherAsync(other, action); }
4779     public CompletionStage<Void> acceptEitherAsync
4780     (CompletionStage<? extends T> other,
4781     Consumer<? super T> action,
4782     Executor executor) {
4783     return cf.acceptEitherAsync(other, action, executor); }
4784     public CompletionStage<Void> runAfterEither
4785     (CompletionStage<?> other,
4786     Runnable action) {
4787     return cf.runAfterEither(other, action); }
4788     public CompletionStage<Void> runAfterEitherAsync
4789     (CompletionStage<?> other,
4790     Runnable action) {
4791     return cf.runAfterEitherAsync(other, action); }
4792     public CompletionStage<Void> runAfterEitherAsync
4793     (CompletionStage<?> other,
4794     Runnable action,
4795     Executor executor) {
4796     return cf.runAfterEitherAsync(other, action, executor); }
4797     public <U> CompletionStage<U> thenCompose
4798     (Function<? super T, ? extends CompletionStage<U>> fn) {
4799     return cf.thenCompose(fn); }
4800     public <U> CompletionStage<U> thenComposeAsync
4801     (Function<? super T, ? extends CompletionStage<U>> fn) {
4802     return cf.thenComposeAsync(fn); }
4803     public <U> CompletionStage<U> thenComposeAsync
4804     (Function<? super T, ? extends CompletionStage<U>> fn,
4805     Executor executor) {
4806     return cf.thenComposeAsync(fn, executor); }
4807     public <U> CompletionStage<U> handle
4808     (BiFunction<? super T, Throwable, ? extends U> fn) {
4809     return cf.handle(fn); }
4810     public <U> CompletionStage<U> handleAsync
4811     (BiFunction<? super T, Throwable, ? extends U> fn) {
4812     return cf.handleAsync(fn); }
4813     public <U> CompletionStage<U> handleAsync
4814     (BiFunction<? super T, Throwable, ? extends U> fn,
4815     Executor executor) {
4816     return cf.handleAsync(fn, executor); }
4817     public CompletionStage<T> whenComplete
4818     (BiConsumer<? super T, ? super Throwable> action) {
4819     return cf.whenComplete(action); }
4820     public CompletionStage<T> whenCompleteAsync
4821     (BiConsumer<? super T, ? super Throwable> action) {
4822     return cf.whenCompleteAsync(action); }
4823     public CompletionStage<T> whenCompleteAsync
4824     (BiConsumer<? super T, ? super Throwable> action,
4825     Executor executor) {
4826     return cf.whenCompleteAsync(action, executor); }
4827     public CompletionStage<T> exceptionally
4828     (Function<Throwable, ? extends T> fn) {
4829     return cf.exceptionally(fn); }
4830     }
4831    
4832     /**
4833 jsr166 1.206 * default-implemented exceptionallyAsync action is not invoked when
4834     * source completes normally, and source result is propagated
4835     */
4836     public void testDefaultExceptionallyAsync_normalCompletion() {
4837     for (boolean createIncomplete : new boolean[] { true, false })
4838     for (Integer v1 : new Integer[] { 1, null })
4839     {
4840     final CompletableFuture<Integer> f = new CompletableFuture<>();
4841     final DelegatedCompletionStage<Integer> d =
4842     new DelegatedCompletionStage<Integer>(f);
4843     if (!createIncomplete) assertTrue(f.complete(v1));
4844     final CompletionStage<Integer> g = d.exceptionallyAsync
4845     ((Throwable t) -> {
4846     threadFail("should not be called");
4847     return null; // unreached
4848     });
4849     if (createIncomplete) assertTrue(f.complete(v1));
4850    
4851     checkCompletedNormally(g.toCompletableFuture(), v1);
4852     }}
4853    
4854     /**
4855 dl 1.199 * default-implemented exceptionallyAsync action completes with
4856     * function value on source exception
4857     */
4858 jsr166 1.204 public void testDefaultExceptionallyAsync_exceptionalCompletion() {
4859 dl 1.199 for (boolean createIncomplete : new boolean[] { true, false })
4860     for (Integer v1 : new Integer[] { 1, null })
4861     {
4862     final AtomicInteger a = new AtomicInteger(0);
4863     final CFException ex = new CFException();
4864     final CompletableFuture<Integer> f = new CompletableFuture<>();
4865     final DelegatedCompletionStage<Integer> d =
4866     new DelegatedCompletionStage<Integer>(f);
4867     if (!createIncomplete) f.completeExceptionally(ex);
4868     final CompletionStage<Integer> g = d.exceptionallyAsync
4869     ((Throwable t) -> {
4870     threadAssertSame(t, ex);
4871     a.getAndIncrement();
4872     return v1;
4873     });
4874     if (createIncomplete) f.completeExceptionally(ex);
4875    
4876     checkCompletedNormally(g.toCompletableFuture(), v1);
4877     assertEquals(1, a.get());
4878     }}
4879    
4880     /**
4881     * Under default implementation, if an "exceptionally action"
4882     * throws an exception, it completes exceptionally with that
4883     * exception
4884     */
4885 jsr166 1.204 public void testDefaultExceptionallyAsync_exceptionalCompletionActionFailed() {
4886 dl 1.199 for (boolean createIncomplete : new boolean[] { true, false })
4887     {
4888     final AtomicInteger a = new AtomicInteger(0);
4889     final CFException ex1 = new CFException();
4890     final CFException ex2 = new CFException();
4891     final CompletableFuture<Integer> f = new CompletableFuture<>();
4892     final DelegatedCompletionStage<Integer> d =
4893     new DelegatedCompletionStage<Integer>(f);
4894     if (!createIncomplete) f.completeExceptionally(ex1);
4895     final CompletionStage<Integer> g = d.exceptionallyAsync
4896     ((Throwable t) -> {
4897     threadAssertSame(t, ex1);
4898     a.getAndIncrement();
4899     throw ex2;
4900     });
4901     if (createIncomplete) f.completeExceptionally(ex1);
4902    
4903     checkCompletedWithWrappedException(g.toCompletableFuture(), ex2);
4904     checkCompletedExceptionally(f, ex1);
4905     checkCompletedExceptionally(d.toCompletableFuture(), ex1);
4906     assertEquals(1, a.get());
4907     }}
4908    
4909     /**
4910 jsr166 1.201 * default exceptionallyCompose result completes normally after normal
4911 dl 1.199 * completion of source
4912     */
4913     public void testDefaultExceptionallyCompose_normalCompletion() {
4914     for (boolean createIncomplete : new boolean[] { true, false })
4915     for (Integer v1 : new Integer[] { 1, null })
4916     {
4917     final CompletableFuture<Integer> f = new CompletableFuture<>();
4918     final ExceptionalCompletableFutureFunction r =
4919     new ExceptionalCompletableFutureFunction(ExecutionMode.SYNC);
4920     final DelegatedCompletionStage<Integer> d =
4921     new DelegatedCompletionStage<Integer>(f);
4922     if (!createIncomplete) assertTrue(f.complete(v1));
4923     final CompletionStage<Integer> g = d.exceptionallyCompose(r);
4924     if (createIncomplete) assertTrue(f.complete(v1));
4925    
4926     checkCompletedNormally(f, v1);
4927     checkCompletedNormally(g.toCompletableFuture(), v1);
4928     r.assertNotInvoked();
4929     }}
4930    
4931     /**
4932     * default-implemented exceptionallyCompose result completes
4933     * normally after exceptional completion of source
4934     */
4935     public void testDefaultExceptionallyCompose_exceptionalCompletion() {
4936     for (boolean createIncomplete : new boolean[] { true, false })
4937     {
4938     final CFException ex = new CFException();
4939     final ExceptionalCompletableFutureFunction r =
4940     new ExceptionalCompletableFutureFunction(ExecutionMode.SYNC);
4941     final CompletableFuture<Integer> f = new CompletableFuture<>();
4942     final DelegatedCompletionStage<Integer> d =
4943     new DelegatedCompletionStage<Integer>(f);
4944     if (!createIncomplete) f.completeExceptionally(ex);
4945     final CompletionStage<Integer> g = d.exceptionallyCompose(r);
4946     if (createIncomplete) f.completeExceptionally(ex);
4947    
4948     checkCompletedExceptionally(f, ex);
4949     checkCompletedNormally(g.toCompletableFuture(), r.value);
4950     r.assertInvoked();
4951     }}
4952    
4953     /**
4954     * default-implemented exceptionallyCompose completes
4955     * exceptionally on exception if action does
4956     */
4957     public void testDefaultExceptionallyCompose_actionFailed() {
4958     for (boolean createIncomplete : new boolean[] { true, false })
4959     for (Integer v1 : new Integer[] { 1, null })
4960     {
4961     final CFException ex = new CFException();
4962     final CompletableFuture<Integer> f = new CompletableFuture<>();
4963     final FailingExceptionalCompletableFutureFunction r
4964     = new FailingExceptionalCompletableFutureFunction(ExecutionMode.SYNC);
4965     final DelegatedCompletionStage<Integer> d =
4966     new DelegatedCompletionStage<Integer>(f);
4967     if (!createIncomplete) f.completeExceptionally(ex);
4968     final CompletionStage<Integer> g = d.exceptionallyCompose(r);
4969     if (createIncomplete) f.completeExceptionally(ex);
4970    
4971     checkCompletedExceptionally(f, ex);
4972     checkCompletedWithWrappedException(g.toCompletableFuture(), r.ex);
4973     r.assertInvoked();
4974     }}
4975    
4976     /**
4977 jsr166 1.201 * default exceptionallyComposeAsync result completes normally after normal
4978 dl 1.199 * completion of source
4979     */
4980     public void testDefaultExceptionallyComposeAsync_normalCompletion() {
4981     for (boolean createIncomplete : new boolean[] { true, false })
4982     for (Integer v1 : new Integer[] { 1, null })
4983     {
4984     final CompletableFuture<Integer> f = new CompletableFuture<>();
4985     final ExceptionalCompletableFutureFunction r =
4986     new ExceptionalCompletableFutureFunction(ExecutionMode.ASYNC);
4987     final DelegatedCompletionStage<Integer> d =
4988     new DelegatedCompletionStage<Integer>(f);
4989     if (!createIncomplete) assertTrue(f.complete(v1));
4990     final CompletionStage<Integer> g = d.exceptionallyComposeAsync(r);
4991     if (createIncomplete) assertTrue(f.complete(v1));
4992    
4993     checkCompletedNormally(f, v1);
4994     checkCompletedNormally(g.toCompletableFuture(), v1);
4995     r.assertNotInvoked();
4996     }}
4997    
4998     /**
4999     * default-implemented exceptionallyComposeAsync result completes
5000     * normally after exceptional completion of source
5001     */
5002     public void testDefaultExceptionallyComposeAsync_exceptionalCompletion() {
5003     for (boolean createIncomplete : new boolean[] { true, false })
5004     {
5005     final CFException ex = new CFException();
5006     final ExceptionalCompletableFutureFunction r =
5007     new ExceptionalCompletableFutureFunction(ExecutionMode.ASYNC);
5008     final CompletableFuture<Integer> f = new CompletableFuture<>();
5009     final DelegatedCompletionStage<Integer> d =
5010     new DelegatedCompletionStage<Integer>(f);
5011     if (!createIncomplete) f.completeExceptionally(ex);
5012     final CompletionStage<Integer> g = d.exceptionallyComposeAsync(r);
5013     if (createIncomplete) f.completeExceptionally(ex);
5014    
5015     checkCompletedExceptionally(f, ex);
5016     checkCompletedNormally(g.toCompletableFuture(), r.value);
5017     r.assertInvoked();
5018     }}
5019    
5020     /**
5021     * default-implemented exceptionallyComposeAsync completes
5022     * exceptionally on exception if action does
5023     */
5024     public void testDefaultExceptionallyComposeAsync_actionFailed() {
5025     for (boolean createIncomplete : new boolean[] { true, false })
5026     for (Integer v1 : new Integer[] { 1, null })
5027     {
5028     final CFException ex = new CFException();
5029     final CompletableFuture<Integer> f = new CompletableFuture<>();
5030     final FailingExceptionalCompletableFutureFunction r
5031     = new FailingExceptionalCompletableFutureFunction(ExecutionMode.ASYNC);
5032     final DelegatedCompletionStage<Integer> d =
5033     new DelegatedCompletionStage<Integer>(f);
5034     if (!createIncomplete) f.completeExceptionally(ex);
5035     final CompletionStage<Integer> g = d.exceptionallyComposeAsync(r);
5036     if (createIncomplete) f.completeExceptionally(ex);
5037    
5038     checkCompletedExceptionally(f, ex);
5039     checkCompletedWithWrappedException(g.toCompletableFuture(), r.ex);
5040     r.assertInvoked();
5041     }}
5042    
5043     /**
5044 jsr166 1.201 * default exceptionallyComposeAsync result completes normally after normal
5045 dl 1.199 * completion of source
5046     */
5047     public void testDefaultExceptionallyComposeAsyncExecutor_normalCompletion() {
5048     for (boolean createIncomplete : new boolean[] { true, false })
5049     for (Integer v1 : new Integer[] { 1, null })
5050     {
5051     final CompletableFuture<Integer> f = new CompletableFuture<>();
5052     final ExceptionalCompletableFutureFunction r =
5053     new ExceptionalCompletableFutureFunction(ExecutionMode.EXECUTOR);
5054     final DelegatedCompletionStage<Integer> d =
5055     new DelegatedCompletionStage<Integer>(f);
5056     if (!createIncomplete) assertTrue(f.complete(v1));
5057 jsr166 1.205 final CompletionStage<Integer> g = d.exceptionallyComposeAsync(r, new ThreadExecutor());
5058 dl 1.199 if (createIncomplete) assertTrue(f.complete(v1));
5059    
5060     checkCompletedNormally(f, v1);
5061     checkCompletedNormally(g.toCompletableFuture(), v1);
5062     r.assertNotInvoked();
5063     }}
5064    
5065     /**
5066     * default-implemented exceptionallyComposeAsync result completes
5067     * normally after exceptional completion of source
5068     */
5069     public void testDefaultExceptionallyComposeAsyncExecutor_exceptionalCompletion() {
5070     for (boolean createIncomplete : new boolean[] { true, false })
5071     {
5072     final CFException ex = new CFException();
5073     final ExceptionalCompletableFutureFunction r =
5074     new ExceptionalCompletableFutureFunction(ExecutionMode.EXECUTOR);
5075     final CompletableFuture<Integer> f = new CompletableFuture<>();
5076     final DelegatedCompletionStage<Integer> d =
5077     new DelegatedCompletionStage<Integer>(f);
5078     if (!createIncomplete) f.completeExceptionally(ex);
5079 jsr166 1.205 final CompletionStage<Integer> g = d.exceptionallyComposeAsync(r, new ThreadExecutor());
5080 dl 1.199 if (createIncomplete) f.completeExceptionally(ex);
5081    
5082     checkCompletedExceptionally(f, ex);
5083     checkCompletedNormally(g.toCompletableFuture(), r.value);
5084     r.assertInvoked();
5085     }}
5086    
5087     /**
5088     * default-implemented exceptionallyComposeAsync completes
5089     * exceptionally on exception if action does
5090     */
5091     public void testDefaultExceptionallyComposeAsyncExecutor_actionFailed() {
5092     for (boolean createIncomplete : new boolean[] { true, false })
5093     for (Integer v1 : new Integer[] { 1, null })
5094     {
5095     final CFException ex = new CFException();
5096     final CompletableFuture<Integer> f = new CompletableFuture<>();
5097     final FailingExceptionalCompletableFutureFunction r
5098     = new FailingExceptionalCompletableFutureFunction(ExecutionMode.EXECUTOR);
5099     final DelegatedCompletionStage<Integer> d =
5100     new DelegatedCompletionStage<Integer>(f);
5101     if (!createIncomplete) f.completeExceptionally(ex);
5102 jsr166 1.205 final CompletionStage<Integer> g = d.exceptionallyComposeAsync(r, new ThreadExecutor());
5103 dl 1.199 if (createIncomplete) f.completeExceptionally(ex);
5104    
5105     checkCompletedExceptionally(f, ex);
5106     checkCompletedWithWrappedException(g.toCompletableFuture(), r.ex);
5107     r.assertInvoked();
5108     }}
5109    
5110 jsr166 1.1 }