< prev index next >

src/java.base/share/classes/java/util/concurrent/CompletableFuture.java

Print this page

 421      * A marker interface identifying asynchronous tasks produced by
 422      * {@code async} methods. This may be useful for monitoring,
 423      * debugging, and tracking asynchronous activities.
 424      *
 425      * @since 1.8
 426      */
 427     public static interface AsynchronousCompletionTask {
 428     }
 429 
 430     private static final boolean USE_COMMON_POOL =
 431         (ForkJoinPool.getCommonPoolParallelism() > 1);
 432 
 433     /**
 434      * Default executor -- ForkJoinPool.commonPool() unless it cannot
 435      * support parallelism.
 436      */
 437     private static final Executor ASYNC_POOL = USE_COMMON_POOL ?
 438         ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();
 439 
 440     /** Fallback if ForkJoinPool.commonPool() cannot support parallelism */
 441     static final class ThreadPerTaskExecutor implements Executor {
 442         public void execute(Runnable r) {
 443             Objects.requireNonNull(r);
 444             new Thread(r).start();
 445         }
 446     }
 447 
 448     /**
 449      * Null-checks user executor argument, and translates uses of
 450      * commonPool to ASYNC_POOL in case parallelism disabled.
 451      */
 452     static Executor screenExecutor(Executor e) {
 453         if (!USE_COMMON_POOL && e == ForkJoinPool.commonPool())
 454             return ASYNC_POOL;
 455         if (e == null) throw new NullPointerException();
 456         return e;
 457     }
 458 
 459     // Modes for Completion.tryFire. Signedness matters.
 460     static final int SYNC   =  0;
 461     static final int ASYNC  =  1;

2117             r = waitingGet(false);
2118         return (T) reportJoin(r);
2119     }
2120 
2121     /**
2122      * Returns the result value (or throws any encountered exception)
2123      * if completed, else returns the given valueIfAbsent.
2124      *
2125      * @param valueIfAbsent the value to return if not completed
2126      * @return the result value, if completed, else the given valueIfAbsent
2127      * @throws CancellationException if the computation was cancelled
2128      * @throws CompletionException if this future completed
2129      * exceptionally or a completion computation threw an exception
2130      */
2131     @SuppressWarnings("unchecked")
2132     public T getNow(T valueIfAbsent) {
2133         Object r;
2134         return ((r = result) == null) ? valueIfAbsent : (T) reportJoin(r);
2135     }
2136 
























2137     /**
2138      * If not already completed, sets the value returned by {@link
2139      * #get()} and related methods to the given value.
2140      *
2141      * @param value the result value
2142      * @return {@code true} if this invocation caused this CompletableFuture
2143      * to transition to a completed state, else {@code false}
2144      */
2145     public boolean complete(T value) {
2146         boolean triggered = completeValue(value);
2147         postComplete();
2148         return triggered;
2149     }
2150 
2151     /**
2152      * If not already completed, causes invocations of {@link #get()}
2153      * and related methods to throw the given exception.
2154      *
2155      * @param ex the exception
2156      * @return {@code true} if this invocation caused this CompletableFuture

2492         Object r;
2493         return ((r = result) instanceof AltResult) &&
2494             (((AltResult)r).ex instanceof CancellationException);
2495     }
2496 
2497     /**
2498      * Returns {@code true} if this CompletableFuture completed
2499      * exceptionally, in any way. Possible causes include
2500      * cancellation, explicit invocation of {@code
2501      * completeExceptionally}, and abrupt termination of a
2502      * CompletionStage action.
2503      *
2504      * @return {@code true} if this CompletableFuture completed
2505      * exceptionally
2506      */
2507     public boolean isCompletedExceptionally() {
2508         Object r;
2509         return ((r = result) instanceof AltResult) && r != NIL;
2510     }
2511 














2512     /**
2513      * Forcibly sets or resets the value subsequently returned by
2514      * method {@link #get()} and related methods, whether or not
2515      * already completed. This method is designed for use only in
2516      * error recovery actions, and even in such situations may result
2517      * in ongoing dependent completions using established versus
2518      * overwritten outcomes.
2519      *
2520      * @param value the completion value
2521      */
2522     public void obtrudeValue(T value) {
2523         result = (value == null) ? NIL : value;
2524         postComplete();
2525     }
2526 
2527     /**
2528      * Forcibly causes subsequent invocations of method {@link #get()}
2529      * and related methods to throw the given exception, whether or
2530      * not already completed. This method is designed for use only in
2531      * error recovery actions, and even in such situations may result

2895                 f.cancel(false);
2896         }
2897     }
2898 
2899     /**
2900      * A subclass that just throws UOE for most non-CompletionStage methods.
2901      */
2902     static final class MinimalStage<T> extends CompletableFuture<T> {
2903         MinimalStage() { }
2904         MinimalStage(Object r) { super(r); }
2905         @Override public <U> CompletableFuture<U> newIncompleteFuture() {
2906             return new MinimalStage<U>(); }
2907         @Override public T get() {
2908             throw new UnsupportedOperationException(); }
2909         @Override public T get(long timeout, TimeUnit unit) {
2910             throw new UnsupportedOperationException(); }
2911         @Override public T getNow(T valueIfAbsent) {
2912             throw new UnsupportedOperationException(); }
2913         @Override public T join() {
2914             throw new UnsupportedOperationException(); }




2915         @Override public boolean complete(T value) {
2916             throw new UnsupportedOperationException(); }
2917         @Override public boolean completeExceptionally(Throwable ex) {
2918             throw new UnsupportedOperationException(); }
2919         @Override public boolean cancel(boolean mayInterruptIfRunning) {
2920             throw new UnsupportedOperationException(); }
2921         @Override public void obtrudeValue(T value) {
2922             throw new UnsupportedOperationException(); }
2923         @Override public void obtrudeException(Throwable ex) {
2924             throw new UnsupportedOperationException(); }
2925         @Override public boolean isDone() {
2926             throw new UnsupportedOperationException(); }
2927         @Override public boolean isCancelled() {
2928             throw new UnsupportedOperationException(); }
2929         @Override public boolean isCompletedExceptionally() {
2930             throw new UnsupportedOperationException(); }


2931         @Override public int getNumberOfDependents() {
2932             throw new UnsupportedOperationException(); }
2933         @Override public CompletableFuture<T> completeAsync
2934             (Supplier<? extends T> supplier, Executor executor) {
2935             throw new UnsupportedOperationException(); }
2936         @Override public CompletableFuture<T> completeAsync
2937             (Supplier<? extends T> supplier) {
2938             throw new UnsupportedOperationException(); }
2939         @Override public CompletableFuture<T> orTimeout
2940             (long timeout, TimeUnit unit) {
2941             throw new UnsupportedOperationException(); }
2942         @Override public CompletableFuture<T> completeOnTimeout
2943             (T value, long timeout, TimeUnit unit) {
2944             throw new UnsupportedOperationException(); }
2945         @Override public CompletableFuture<T> toCompletableFuture() {
2946             Object r;
2947             if ((r = result) != null)
2948                 return new CompletableFuture<T>(encodeRelay(r));
2949             else {
2950                 CompletableFuture<T> d = new CompletableFuture<>();

 421      * A marker interface identifying asynchronous tasks produced by
 422      * {@code async} methods. This may be useful for monitoring,
 423      * debugging, and tracking asynchronous activities.
 424      *
 425      * @since 1.8
 426      */
 427     public static interface AsynchronousCompletionTask {
 428     }
 429 
 430     private static final boolean USE_COMMON_POOL =
 431         (ForkJoinPool.getCommonPoolParallelism() > 1);
 432 
 433     /**
 434      * Default executor -- ForkJoinPool.commonPool() unless it cannot
 435      * support parallelism.
 436      */
 437     private static final Executor ASYNC_POOL = USE_COMMON_POOL ?
 438         ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();
 439 
 440     /** Fallback if ForkJoinPool.commonPool() cannot support parallelism */
 441     private static final class ThreadPerTaskExecutor implements Executor {
 442         public void execute(Runnable r) {
 443             Objects.requireNonNull(r);
 444             new Thread(r).start();
 445         }
 446     }
 447 
 448     /**
 449      * Null-checks user executor argument, and translates uses of
 450      * commonPool to ASYNC_POOL in case parallelism disabled.
 451      */
 452     static Executor screenExecutor(Executor e) {
 453         if (!USE_COMMON_POOL && e == ForkJoinPool.commonPool())
 454             return ASYNC_POOL;
 455         if (e == null) throw new NullPointerException();
 456         return e;
 457     }
 458 
 459     // Modes for Completion.tryFire. Signedness matters.
 460     static final int SYNC   =  0;
 461     static final int ASYNC  =  1;

2117             r = waitingGet(false);
2118         return (T) reportJoin(r);
2119     }
2120 
2121     /**
2122      * Returns the result value (or throws any encountered exception)
2123      * if completed, else returns the given valueIfAbsent.
2124      *
2125      * @param valueIfAbsent the value to return if not completed
2126      * @return the result value, if completed, else the given valueIfAbsent
2127      * @throws CancellationException if the computation was cancelled
2128      * @throws CompletionException if this future completed
2129      * exceptionally or a completion computation threw an exception
2130      */
2131     @SuppressWarnings("unchecked")
2132     public T getNow(T valueIfAbsent) {
2133         Object r;
2134         return ((r = result) == null) ? valueIfAbsent : (T) reportJoin(r);
2135     }
2136 
2137     @Override
2138     public T completedResultNow() {
2139         Object r = result;
2140         if (r != null) {
2141             if (r instanceof AltResult alt) {
2142                 if (alt.ex == null) return null;
2143             } else {
2144                 @SuppressWarnings("unchecked")
2145                 T t = (T) r;
2146                 return t;
2147             }
2148         }
2149         throw new IllegalStateException();
2150     }
2151 
2152     @Override
2153     public Throwable completedExceptionNow() {
2154         Object r = result;
2155         if (r instanceof AltResult alt && alt.ex != null) {
2156             return alt.ex;
2157         }
2158         throw new IllegalStateException();
2159     }
2160 
2161     /**
2162      * If not already completed, sets the value returned by {@link
2163      * #get()} and related methods to the given value.
2164      *
2165      * @param value the result value
2166      * @return {@code true} if this invocation caused this CompletableFuture
2167      * to transition to a completed state, else {@code false}
2168      */
2169     public boolean complete(T value) {
2170         boolean triggered = completeValue(value);
2171         postComplete();
2172         return triggered;
2173     }
2174 
2175     /**
2176      * If not already completed, causes invocations of {@link #get()}
2177      * and related methods to throw the given exception.
2178      *
2179      * @param ex the exception
2180      * @return {@code true} if this invocation caused this CompletableFuture

2516         Object r;
2517         return ((r = result) instanceof AltResult) &&
2518             (((AltResult)r).ex instanceof CancellationException);
2519     }
2520 
2521     /**
2522      * Returns {@code true} if this CompletableFuture completed
2523      * exceptionally, in any way. Possible causes include
2524      * cancellation, explicit invocation of {@code
2525      * completeExceptionally}, and abrupt termination of a
2526      * CompletionStage action.
2527      *
2528      * @return {@code true} if this CompletableFuture completed
2529      * exceptionally
2530      */
2531     public boolean isCompletedExceptionally() {
2532         Object r;
2533         return ((r = result) instanceof AltResult) && r != NIL;
2534     }
2535 
2536     @Override
2537     public State state() {
2538         Object r = result;
2539         if (r == null)
2540             return State.RUNNING;
2541         if (r != NIL && r instanceof AltResult alt) {
2542             if (alt.ex instanceof CancellationException)
2543                 return State.CANCELLED;
2544             else
2545                 return State.FAILED;
2546         }
2547         return State.SUCCESS;
2548     }
2549 
2550     /**
2551      * Forcibly sets or resets the value subsequently returned by
2552      * method {@link #get()} and related methods, whether or not
2553      * already completed. This method is designed for use only in
2554      * error recovery actions, and even in such situations may result
2555      * in ongoing dependent completions using established versus
2556      * overwritten outcomes.
2557      *
2558      * @param value the completion value
2559      */
2560     public void obtrudeValue(T value) {
2561         result = (value == null) ? NIL : value;
2562         postComplete();
2563     }
2564 
2565     /**
2566      * Forcibly causes subsequent invocations of method {@link #get()}
2567      * and related methods to throw the given exception, whether or
2568      * not already completed. This method is designed for use only in
2569      * error recovery actions, and even in such situations may result

2933                 f.cancel(false);
2934         }
2935     }
2936 
2937     /**
2938      * A subclass that just throws UOE for most non-CompletionStage methods.
2939      */
2940     static final class MinimalStage<T> extends CompletableFuture<T> {
2941         MinimalStage() { }
2942         MinimalStage(Object r) { super(r); }
2943         @Override public <U> CompletableFuture<U> newIncompleteFuture() {
2944             return new MinimalStage<U>(); }
2945         @Override public T get() {
2946             throw new UnsupportedOperationException(); }
2947         @Override public T get(long timeout, TimeUnit unit) {
2948             throw new UnsupportedOperationException(); }
2949         @Override public T getNow(T valueIfAbsent) {
2950             throw new UnsupportedOperationException(); }
2951         @Override public T join() {
2952             throw new UnsupportedOperationException(); }
2953         @Override public T completedResultNow() {
2954             throw new UnsupportedOperationException(); }
2955         @Override public Throwable completedExceptionNow() {
2956             throw new UnsupportedOperationException(); }
2957         @Override public boolean complete(T value) {
2958             throw new UnsupportedOperationException(); }
2959         @Override public boolean completeExceptionally(Throwable ex) {
2960             throw new UnsupportedOperationException(); }
2961         @Override public boolean cancel(boolean mayInterruptIfRunning) {
2962             throw new UnsupportedOperationException(); }
2963         @Override public void obtrudeValue(T value) {
2964             throw new UnsupportedOperationException(); }
2965         @Override public void obtrudeException(Throwable ex) {
2966             throw new UnsupportedOperationException(); }
2967         @Override public boolean isDone() {
2968             throw new UnsupportedOperationException(); }
2969         @Override public boolean isCancelled() {
2970             throw new UnsupportedOperationException(); }
2971         @Override public boolean isCompletedExceptionally() {
2972             throw new UnsupportedOperationException(); }
2973         @Override public State state() {
2974             throw new UnsupportedOperationException(); }
2975         @Override public int getNumberOfDependents() {
2976             throw new UnsupportedOperationException(); }
2977         @Override public CompletableFuture<T> completeAsync
2978             (Supplier<? extends T> supplier, Executor executor) {
2979             throw new UnsupportedOperationException(); }
2980         @Override public CompletableFuture<T> completeAsync
2981             (Supplier<? extends T> supplier) {
2982             throw new UnsupportedOperationException(); }
2983         @Override public CompletableFuture<T> orTimeout
2984             (long timeout, TimeUnit unit) {
2985             throw new UnsupportedOperationException(); }
2986         @Override public CompletableFuture<T> completeOnTimeout
2987             (T value, long timeout, TimeUnit unit) {
2988             throw new UnsupportedOperationException(); }
2989         @Override public CompletableFuture<T> toCompletableFuture() {
2990             Object r;
2991             if ((r = result) != null)
2992                 return new CompletableFuture<T>(encodeRelay(r));
2993             else {
2994                 CompletableFuture<T> d = new CompletableFuture<>();
< prev index next >