54 |
|
* |
55 |
|
* <li>All CompletionStage methods return CompletableFutures. To |
56 |
|
* restrict usages to only those methods defined in interface |
57 |
< |
* CompletionStage, use the new CompletionStage from method {@link |
58 |
< |
* minimalCompletionStage}. Or to ensure only that clients do not |
59 |
< |
* themselves modify a future, use method {@link copy}. </li> </ul> |
57 |
> |
* CompletionStage, use method {@link #minimalCompletionStage}. Or to |
58 |
> |
* ensure only that clients do not themselves modify a future, use |
59 |
> |
* method {@link copy}. </li> </ul> |
60 |
|
* |
61 |
|
* <p>CompletableFuture also implements {@link Future} with the following |
62 |
|
* policies: <ul> |
2501 |
|
} |
2502 |
|
|
2503 |
|
/** |
2504 |
+ |
* Completes this CompletableFuture with the given value if not |
2505 |
+ |
* otherwise completed before the given timeout. |
2506 |
+ |
* |
2507 |
+ |
* @param value the value to use upon timeout |
2508 |
+ |
* @param timeout how long to wait before completing. |
2509 |
+ |
* @param unit a {@code TimeUnit} determining how to interpret the |
2510 |
+ |
* {@code timeout} parameter |
2511 |
+ |
* @return this CompletableFuture |
2512 |
+ |
* @since 1.9 |
2513 |
+ |
*/ |
2514 |
+ |
public CompletableFuture<T> completeOnTimeout(T value, long timeout, |
2515 |
+ |
TimeUnit unit) { |
2516 |
+ |
if (result == null) |
2517 |
+ |
whenComplete(new Canceller(Delayer.delay( |
2518 |
+ |
new DelayedCompleter<T>(this, value), |
2519 |
+ |
timeout, unit))); |
2520 |
+ |
return this; |
2521 |
+ |
} |
2522 |
+ |
|
2523 |
+ |
/** |
2524 |
|
* Returns a new Executor that submits a task to the given base |
2525 |
|
* executor after the given delay. |
2526 |
|
* |
2656 |
|
} |
2657 |
|
} |
2658 |
|
|
2659 |
+ |
/** Action to completeExceptionally on timeout */ |
2660 |
+ |
static final class DelayedCompleter<U> implements Runnable { |
2661 |
+ |
final CompletableFuture<U> f; |
2662 |
+ |
final U u; |
2663 |
+ |
DelayedCompleter(CompletableFuture<U> f, U u) { this.f = f; this.u = u; } |
2664 |
+ |
public void run() { f.complete(u); } |
2665 |
+ |
} |
2666 |
+ |
|
2667 |
|
/** Action to cancel unneeded timeouts */ |
2668 |
|
static final class Canceller implements BiConsumer<Object, Throwable> { |
2669 |
|
final Future<?> f; |