< 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 resultNow() {
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 exceptionNow() {
2154         Object r = result;
2155         Throwable x;
2156         if (r instanceof AltResult alt
2157                 && ((x = alt.ex) != null)
2158                 && !(x instanceof CancellationException)) {
2159             if (x instanceof CompletionException) {
2160                 Throwable cause = x.getCause();
2161                 if (cause != null)
2162                     x = cause;
2163             }
2164             return x;
2165         }
2166         throw new IllegalStateException();
2167     }
2168 
2169     /**
2170      * If not already completed, sets the value returned by {@link
2171      * #get()} and related methods to the given value.
2172      *
2173      * @param value the result value
2174      * @return {@code true} if this invocation caused this CompletableFuture
2175      * to transition to a completed state, else {@code false}
2176      */
2177     public boolean complete(T value) {
2178         boolean triggered = completeValue(value);
2179         postComplete();
2180         return triggered;
2181     }
2182 
2183     /**
2184      * If not already completed, causes invocations of {@link #get()}
2185      * and related methods to throw the given exception.
2186      *
2187      * @param ex the exception
2188      * @return {@code true} if this invocation caused this CompletableFuture

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

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