Interface Future<T>
- Type Parameters:
T- the type of the computation result
- All Known Implementing Classes:
FutureImpl
Future are non-blocking.
The underlying Executor is used to execute asynchronous handlers, for example via
onComplete(...).
A Future has two states:
- Pending: The computation is ongoing. Only a pending future may be completed or cancelled.
- Completed: The computation has finished, either successfully with a result, with an exception, or via cancellation.
Callbacks may be registered on a Future at any time. These callbacks are executed as soon as the
Future completes. If a callback is registered on a completed Future, it is executed immediately.
Execution may occur on a separate thread, depending on the underlying Executor. Callbacks registered
on a cancelled Future are executed with the failed result.
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final ExecutorThe default executor isForkJoinPool.commonPool(). -
Method Summary
Modifier and TypeMethodDescriptionSupports chaining of callbacks that are guaranteed to be executed in order.await()Blocks the current thread until thisFutureis completed, or returns immediately if it is already completed.Blocks the current thread until thisFutureis completed, or returns immediately if it is already completed.default booleancancel()Cancels thisFuture.booleancancel(boolean mayInterruptIfRunning) Cancels thisFuture.default <R> Future<R> collect(@NonNull PartialFunction<? super T, ? extends R> partialFunction) Applies apartialFunctionto the value of thisFuture, collecting results only for values where the function is defined.default Executorexecutor()Returns theExecutorthat executes asynchronous handlers for thisFuture.Deprecated.failed()Returns a projection that inverts the result of thisFuture.static <T> Future<T> static <T> Future<T> fallbackTo(@NonNull Future<? extends T> that) Returns aFuturethat yields the result of thisFutureif it succeeds.Shortcut forfilterTry(predicate::test), filtering the result of thisFutureusing the given predicate.filterTry(@NonNull CheckedPredicate<? super T> predicate) Filters the result of thisFutureusing the givenCheckedPredicate, delegating toTry.filterTry(CheckedPredicate).find(@NonNull Iterable<? extends Future<? extends T>> futures, @NonNull Predicate<? super T> predicate) Returns aFuturethat completes with the first result of the givenfuturesthat satisfies the specifiedpredicate.find(@NonNull Executor executor, @NonNull Iterable<? extends Future<? extends T>> futures, @NonNull Predicate<? super T> predicate) Returns aFuturethat completes with the first result of the givenfuturesthat satisfies the specifiedpredicate.static <T> Future<T> firstCompletedOf(@NonNull Iterable<? extends Future<? extends T>> futures) Returns a newFuturethat completes with the result of the first future in the given iterable that completes, using theDEFAULT_EXECUTOR.static <T> Future<T> firstCompletedOf(@NonNull Executor executor, @NonNull Iterable<? extends Future<? extends T>> futures) Returns a newFuturethat completes with the result of the first future in the given iterable that completes, using the specifiedExecutor.default <U> Future<U> Transforms the value of thisFutureusing the givenFunctionif it completes successfully, or returns aFuturewith the failure if thisFuturefails.default <U> Future<U> flatMapTry(@NonNull CheckedFunction1<? super T, ? extends Future<? extends U>> mapper) Transforms the value of thisFutureusing the givenCheckedFunction1if it completes successfully, or returns aFuturewith the failure if thisFuturefails.static <T,U> Future <U> fold(@NonNull Iterable<? extends Future<? extends T>> futures, U zero, @NonNull BiFunction<? super U, ? super T, ? extends U> f) Returns aFuturethat contains the result of folding the given future values.static <T,U> Future <U> fold(@NonNull Executor executor, @NonNull Iterable<? extends Future<? extends T>> futures, U zero, @NonNull BiFunction<? super U, ? super T, ? extends U> f) Returns aFuturecontaining the result of folding the given future values.default voidPerforms the givenactionasynchronously when thisFuturecompletes successfully.static <T> Future<T> fromCompletableFuture(@NonNull CompletableFuture<T> future) Creates aFuturethat wraps the givenCompletableFuture, using theDEFAULT_EXECUTORfor executing callbacks.static <T> Future<T> fromCompletableFuture(@NonNull Executor executor, @NonNull CompletableFuture<T> future) Creates aFuturethat wraps the givenCompletableFuture, executing callbacks using the specifiedExecutor.static <T> Future<T> fromJavaFuture(@NonNull Executor executor, @NonNull Future<T> future) static <T> Future<T> fromJavaFuture(@NonNull Future<T> future) static <T> Future<T> static <T> Future<T> default Tget()Returns the value of thisFutureif it completed successfully, or throws the underlying exception if it completed with a failure.getCause()Returns the underlying exception.getValue()Returns the value of thisFuture.default booleanisAsync()AFutures's value is computed asynchronously.booleanChecks whether thisFuturewas cancelled, i.e., its computation was interrupted before completion.booleanChecks whether thisFutureis completed, i.e., whether it has finished with a value, failed, or was cancelled.default booleanisEmpty()Checks, if this future has a value.default booleanChecks whether thisFuturecompleted with a failure.default booleanisLazy()AFuture's value is computed eagerly.default booleanAFutureis single-valued.default booleanChecks whether thisFuturecompleted successfully.iterator()Returns a richio.vavr.collection.Iterator.default <U> Future<U> Maps the underlying value to a different component type.default <U> Future<U> mapTo(U value) Maps the underlying value to another fixed value.Maps the underlying value to Voiddefault <U> Future<U> mapTry(@NonNull CheckedFunction1<? super T, ? extends U> mapper) Maps the value of thisFutureto a new value using the givenCheckedFunction1if it completes successfully.static <T> Future<T> Narrows aFuture<? extends T>toFuture<T>via a type-safe cast.static <T> Future<T> of(@NonNull CheckedFunction0<? extends T> computation) Starts an asynchronous computation using theDEFAULT_EXECUTOR.static <T> Future<T> of(@NonNull Executor executor, @NonNull CheckedFunction0<? extends T> computation) Starts an asynchronous computation using the specifiedExecutor.onComplete(@NonNull Consumer<? super Try<T>> action) Performs the given action once thisFutureis complete.Performs the given action once thisFutureis complete and its result is aTry.Failure.Performs the given action once thisFutureis complete and its result is aTry.Success.Returns thisFutureif it completes successfully, or the given alternativeFutureif thisFuturefails.Returns thisFutureif it completes successfully, or aFuturesupplied by the givenSupplierif thisFuturefails.Performs the givenactionon the first element if this is an eager implementation.Handles a failure of thisFutureby mapping the exception to a new result.recoverWith(@NonNull Function<? super Throwable, ? extends Future<? extends T>> f) Handles a failure of thisFutureby returning the result of anotherFuture.static <T> Future<T> reduce(@NonNull Iterable<? extends Future<? extends T>> futures, @NonNull BiFunction<? super T, ? super T, ? extends T> f) Returns aFuturecontaining the result of reducing the given future values.static <T> Future<T> reduce(@NonNull Executor executor, @NonNull Iterable<? extends Future<? extends T>> futures, @NonNull BiFunction<? super T, ? super T, ? extends T> f) Returns aFuturecontaining the result of reducing the given future values.run(@NonNull CheckedRunnable unit) Runs an asynchronous computation using theDEFAULT_EXECUTOR.run(@NonNull Executor executor, @NonNull CheckedRunnable unit) Starts an asynchronous computation using the specifiedExecutor.Reduces multipleFutureinstances into a singleFutureby transforming anIterable<Future<? extends T>>into aFuture<Seq<T>>.Reduces multipleFutureinstances into a singleFutureby transforming anIterable<Future<? extends T>>into aFuture<Seq<T>>.default StringReturns the name of this Value type, which is used by toString().static <T> Future<T> successful(@NonNull Executor executor, T result) Creates a succeededFuturewith the given result, executing callbacks using the specifiedExecutor.static <T> Future<T> successful(T result) Creates a succeededFuturewith the given result, using theDEFAULT_EXECUTORto execute callbacks.default CompletableFuture<T> Converts this to aCompletableFuturedefault <U> UTransforms the result of thisFutureusing the given function.default <U> Future<U> transformValue(@NonNull Function<? super Try<T>, ? extends Try<? extends U>> f) Transforms the value of thisFuture, regardless of whether it completed successfully or with a failure.traverse(@NonNull Iterable<? extends T> values, @NonNull Function<? super T, ? extends Future<? extends U>> mapper) Maps the values of an iterable in parallel to a sequence of mapped values, producing a singleFutureby transforming anIterable<? extends T>into aFuture<Seq<U>>.traverse(@NonNull Executor executor, @NonNull Iterable<? extends T> values, @NonNull Function<? super T, ? extends Future<? extends U>> mapper) Maps the values of an iterable in parallel to a sequence of mapped values, producing a singleFutureby transforming anIterable<? extends T>into aFuture<Seq<U>>.Combines thisFuturewith anotherFuture, returning aFutureof a tuple of both results.default <U,R> Future <R> zipWith(@NonNull Future<? extends U> that, @NonNull BiFunction<? super T, ? super U, ? extends R> combinator) Combines thisFuturewith anotherFutureusing the given combinator function.Methods inherited from interface Value
collect, collect, contains, corresponds, eq, equals, exists, forAll, getOrElse, getOrElse, getOrElseThrow, getOrElseTry, getOrNull, hashCode, out, out, spliterator, stderr, stdout, toArray, toCharSeq, toEither, toEither, toInvalid, toInvalid, toJavaArray, toJavaArray, toJavaArray, toJavaCollection, toJavaList, toJavaList, toJavaMap, toJavaMap, toJavaMap, toJavaOptional, toJavaParallelStream, toJavaSet, toJavaSet, toJavaStream, toLeft, toLeft, toLinkedMap, toLinkedMap, toLinkedSet, toList, toMap, toMap, toOption, toPriorityQueue, toPriorityQueue, toQueue, toRight, toRight, toSet, toSortedMap, toSortedMap, toSortedMap, toSortedMap, toSortedSet, toSortedSet, toStream, toString, toTree, toTree, toTry, toTry, toValid, toValid, toValidation, toValidation, toVector
-
Field Details
-
DEFAULT_EXECUTOR
The default executor isForkJoinPool.commonPool().Facts about ForkJoinPool:
- It is work-stealing, i.e. all threads in the pool attempt to find work submitted to the pool. Especially this is efficient under heavy load (many small tasks), e.g. when tasks create subtasks (recursive threads).
- The ForkJoinPool is dynamic, it has a maximum of 32767 running threads. Compared to fixed-size pools, this reduces the risk of dead-locks.
- The commonPool() is shared across the entire VM. Keep this in mind when also using
BaseStream.parallel()andCompletableFuture}
IMPORTANT: Invoke
ForkJoinPool.commonPool().awaitQuiescence(long, TimeUnit)before exit in order to ensure that all running async tasks complete before program termination.- See Also:
-
-
Method Details
-
failed
- Type Parameters:
T- the type of a successful result- Parameters:
exception- the exception that caused the failure- Returns:
- a failed
Futurecontaining the given exception - Throws:
NullPointerException- ifexceptionis null
-
failed
- Type Parameters:
T- the type of a successful result- Parameters:
executor- theExecutorto run asynchronous handlersexception- the exception that caused the failure- Returns:
- a failed
Futurecontaining the given exception - Throws:
NullPointerException- ifexecutororexceptionis null
-
find
static <T> Future<Option<T>> find(@NonNull Iterable<? extends Future<? extends T>> futures, @NonNull Predicate<? super T> predicate) Returns aFuturethat completes with the first result of the givenfuturesthat satisfies the specifiedpredicate. If no result matches, theFuturewill containOption.None.The returned
Futureuses theDEFAULT_EXECUTORto execute callbacks.- Type Parameters:
T- the type of the future results- Parameters:
futures- an iterable of futures to inspectpredicate- a predicate to test successful future results- Returns:
- a
Futureof anOptioncontaining the first matching result, orOption.Noneif none match - Throws:
NullPointerException- iffuturesorpredicateis null
-
find
static <T> Future<Option<T>> find(@NonNull Executor executor, @NonNull Iterable<? extends Future<? extends T>> futures, @NonNull Predicate<? super T> predicate) Returns aFuturethat completes with the first result of the givenfuturesthat satisfies the specifiedpredicate. If no result matches, theFuturewill containOption.None.The returned
Futureexecutes using the providedExecutor.- Type Parameters:
T- the type of the future results- Parameters:
executor- theExecutorto run asynchronous handlersfutures- an iterable of futures to inspectpredicate- a predicate to test successful future results- Returns:
- a
Futureof anOptioncontaining the first matching result, orOption.Noneif none match - Throws:
NullPointerException- if any argument is null
-
firstCompletedOf
Returns a newFuturethat completes with the result of the first future in the given iterable that completes, using theDEFAULT_EXECUTOR.- Type Parameters:
T- the type of the future results- Parameters:
futures- an iterable of futures to observe- Returns:
- a new
Futurecontaining the result of the first completed future - Throws:
NullPointerException- iffuturesis null
-
firstCompletedOf
static <T> Future<T> firstCompletedOf(@NonNull Executor executor, @NonNull Iterable<? extends Future<? extends T>> futures) Returns a newFuturethat completes with the result of the first future in the given iterable that completes, using the specifiedExecutor.- Type Parameters:
T- the type of the future results- Parameters:
executor- theExecutorto run asynchronous handlersfutures- an iterable of futures to observe- Returns:
- a new
Futurecontaining the result of the first completed future - Throws:
NullPointerException- ifexecutororfuturesis null
-
fold
static <T,U> Future<U> fold(@NonNull Iterable<? extends Future<? extends T>> futures, U zero, @NonNull BiFunction<? super U, ? super T, ? extends U> f) Returns aFuturethat contains the result of folding the given future values. If any future fails or the fold operation throws an exception, the resultingFuturewill also fail.The resulting
Futureexecutes using theDEFAULT_EXECUTOR.- Type Parameters:
T- the type of the values in the given futuresU- the result type of the fold- Parameters:
futures- an iterable of futures to foldzero- the initial value for the foldf- the fold operation- Returns:
- a new
Futurecontaining the fold result - Throws:
NullPointerException- iffuturesorfis null
-
fold
static <T,U> Future<U> fold(@NonNull Executor executor, @NonNull Iterable<? extends Future<? extends T>> futures, U zero, @NonNull BiFunction<? super U, ? super T, ? extends U> f) Returns aFuturecontaining the result of folding the given future values. If any future fails or the fold operation throws an exception, the resultingFuturewill also fail.The resulting
Futureexecutes using the specifiedExecutor.- Type Parameters:
T- the type of the values in the given futuresU- the result type of the fold- Parameters:
executor- theExecutorto run asynchronous handlersfutures- an iterable of futures to foldzero- the initial value for the foldf- the fold operation- Returns:
- a new
Futurecontaining the fold result - Throws:
NullPointerException- ifexecutor,futures, orfis null
-
fromJavaFuture
- Type Parameters:
T- the result type of the future- Parameters:
future- theFutureto wrap- Returns:
- a new
Futurecontaining the result of the given Java future - Throws:
NullPointerException- iffutureis null
-
fromJavaFuture
- Type Parameters:
T- the result type of the future- Parameters:
executor- theExecutorto run asynchronous handlersfuture- theFutureto wrap- Returns:
- a new
Futurecontaining the result of the given Java future - Throws:
NullPointerException- ifexecutororfutureis null
-
fromCompletableFuture
Creates aFuturethat wraps the givenCompletableFuture, using theDEFAULT_EXECUTORfor executing callbacks.- Type Parameters:
T- the result type of the future- Parameters:
future- theCompletableFutureto wrap- Returns:
- a new
Futurecontaining the result of the givenCompletableFuture - Throws:
NullPointerException- iffutureis null
-
fromCompletableFuture
@GwtIncompatible static <T> Future<T> fromCompletableFuture(@NonNull Executor executor, @NonNull CompletableFuture<T> future) Creates aFuturethat wraps the givenCompletableFuture, executing callbacks using the specifiedExecutor.- Type Parameters:
T- the result type of the future- Parameters:
executor- theExecutorto run asynchronous handlersfuture- theCompletableFutureto wrap- Returns:
- a new
Futurecontaining the result of the givenCompletableFuture - Throws:
NullPointerException- ifexecutororfutureis null
-
fromTry
- Type Parameters:
T- the type of a successful result- Parameters:
result- theTryresult to wrap- Returns:
- a completed
Futurecontaining either aSuccessor aFailure - Throws:
NullPointerException- ifresultis null
-
fromTry
- Type Parameters:
T- the type of successful result- Parameters:
executor- theExecutorto run asynchronous handlersresult- theTryresult to wrap- Returns:
- a completed
Futurecontaining either aSuccessor aFailure - Throws:
NullPointerException- ifexecutororresultis null
-
narrow
Narrows aFuture<? extends T>toFuture<T>via a type-safe cast. This is safe because immutable or read-only collections are covariant.- Type Parameters:
T- the type of the value contained in the future- Parameters:
future- theFutureto narrow- Returns:
- the given
futureinstance as aFuture<T>
-
of
Starts an asynchronous computation using theDEFAULT_EXECUTOR.- Type Parameters:
T- the type of the computation result- Parameters:
computation- the computation to execute asynchronously- Returns:
- a new
Futurecontaining the result of the computation - Throws:
NullPointerException- ifcomputationis null
-
of
static <T> Future<T> of(@NonNull Executor executor, @NonNull CheckedFunction0<? extends T> computation) Starts an asynchronous computation using the specifiedExecutor.- Type Parameters:
T- the type of the computation result- Parameters:
executor- theExecutorto run asynchronous handlerscomputation- the computation to execute asynchronously- Returns:
- a new
Futurecontaining the result of the computation - Throws:
NullPointerException- ifexecutororcomputationis null
-
reduce
static <T> Future<T> reduce(@NonNull Iterable<? extends Future<? extends T>> futures, @NonNull BiFunction<? super T, ? super T, ? extends T> f) Returns aFuturecontaining the result of reducing the given future values. The first completed future serves as the initial (zero) value. If any future or the reduce operation fails, the resultingFuturewill also fail.The resulting
Futureexecutes using theDEFAULT_EXECUTOR.- Type Parameters:
T- the type of the values in the given futures- Parameters:
futures- an iterable of futures to reducef- the reduce operation- Returns:
- a new
Futurecontaining the reduce result - Throws:
NullPointerException- iffuturesorfis null
-
reduce
static <T> Future<T> reduce(@NonNull Executor executor, @NonNull Iterable<? extends Future<? extends T>> futures, @NonNull BiFunction<? super T, ? super T, ? extends T> f) Returns aFuturecontaining the result of reducing the given future values. The first completed future serves as the initial (zero) value. If any future or the reduce operation fails, the resultingFuturewill also fail.The resulting
Futureexecutes using the specifiedExecutor.- Type Parameters:
T- the type of the values in the given futures- Parameters:
executor- theExecutorto run asynchronous handlersfutures- an iterable of futures to reducef- the reduce operation- Returns:
- a new
Futurecontaining the reduce result - Throws:
NullPointerException- ifexecutor,futures, orfis null
-
run
Runs an asynchronous computation using theDEFAULT_EXECUTOR.- Parameters:
unit- a unit of work to execute asynchronously- Returns:
- a new
Futurerepresenting the completion of the computation, with no result - Throws:
NullPointerException- ifunitis null
-
run
Starts an asynchronous computation using the specifiedExecutor.- Parameters:
executor- theExecutorto run asynchronous handlersunit- a unit of work to execute asynchronously- Returns:
- a new
Futurerepresenting the completion of the computation, with no result - Throws:
NullPointerException- ifexecutororunitis null
-
sequence
Reduces multipleFutureinstances into a singleFutureby transforming anIterable<Future<? extends T>>into aFuture<Seq<T>>.The resulting
Futureexecutes using theDEFAULT_EXECUTOR.-
If all given futures succeed, the resulting future also succeeds:
// = Future(Success(Seq(1, 2))) sequence( List.of( Future.of(() -> 1), Future.of(() -> 2) ) ); -
If any given future fails, the resulting future fails as well:
// = Future(Failure(Error)) sequence( List.of( Future.of(() -> 1), Future.of(() -> { throw new Error(); }) ) );
- Type Parameters:
T- the result type of the futures- Parameters:
futures- anIterableofFutures- Returns:
- a
Futurecontaining aSeqof results - Throws:
NullPointerException- iffuturesis null
-
If all given futures succeed, the resulting future also succeeds:
-
sequence
static <T> Future<Seq<T>> sequence(@NonNull Executor executor, @NonNull Iterable<? extends Future<? extends T>> futures) Reduces multipleFutureinstances into a singleFutureby transforming anIterable<Future<? extends T>>into aFuture<Seq<T>>.The resulting
Futureexecutes using the specifiedExecutor.- Type Parameters:
T- the result type of the futures- Parameters:
executor- theExecutorto run asynchronous handlersfutures- anIterableofFutures to reduce- Returns:
- a
Futurecontaining aSeqof results - Throws:
NullPointerException- ifexecutororfuturesis null
-
successful
Creates a succeededFuturewith the given result, using theDEFAULT_EXECUTORto execute callbacks.- Type Parameters:
T- the type of the result- Parameters:
result- the successful result- Returns:
- a succeeded
Futurecontaining the given result
-
successful
Creates a succeededFuturewith the given result, executing callbacks using the specifiedExecutor.- Type Parameters:
T- the type of the result- Parameters:
executor- theExecutorto run asynchronous handlersresult- the successful result- Returns:
- a succeeded
Futurecontaining the given result - Throws:
NullPointerException- ifexecutoris null
-
toCompletableFuture
Description copied from interface:ValueConverts this to aCompletableFuture- Specified by:
toCompletableFuturein interfaceValue<T>- Returns:
- A new
CompletableFuturecontaining the value
-
traverse
static <T,U> Future<Seq<U>> traverse(@NonNull Iterable<? extends T> values, @NonNull Function<? super T, ? extends Future<? extends U>> mapper) Maps the values of an iterable in parallel to a sequence of mapped values, producing a singleFutureby transforming anIterable<? extends T>into aFuture<Seq<U>>.The resulting
Futureexecutes using theDEFAULT_EXECUTOR.- Type Parameters:
T- the type of the input valuesU- the type of the mapped values- Parameters:
values- anIterableof input valuesmapper- a function mapping values toFutures- Returns:
- a
Futurecontaining aSeqof mapped results - Throws:
NullPointerException- ifvaluesormapperis null
-
traverse
static <T,U> Future<Seq<U>> traverse(@NonNull Executor executor, @NonNull Iterable<? extends T> values, @NonNull Function<? super T, ? extends Future<? extends U>> mapper) Maps the values of an iterable in parallel to a sequence of mapped values, producing a singleFutureby transforming anIterable<? extends T>into aFuture<Seq<U>>.The resulting
Futureexecutes using the specifiedExecutor.- Type Parameters:
T- the type of the input valuesU- the type of the mapped values- Parameters:
executor- theExecutorto run asynchronous handlersvalues- anIterableof input valuesmapper- a function mapping values toFutures- Returns:
- a
Futurecontaining aSeqof mapped results - Throws:
NullPointerException- ifexecutor,values, ormapperis null
-
andThen
Supports chaining of callbacks that are guaranteed to be executed in order.Exceptions thrown by the given
actionare not propagated. Subsequent actions are executed based on the value of the originalFuture.Example:
// prints Success(1) Future.of(() -> 1) .andThen(t -> { throw new Error(""); }) .andThen(System.out::println);- Parameters:
action- a side-effecting action to perform after the future completes- Returns:
- a new
Futurecontaining the original result, completed after the action executes - Throws:
NullPointerException- ifactionis null
-
await
Blocks the current thread until thisFutureis completed, or returns immediately if it is already completed.If the current thread is interrupted while waiting, a failed
Futureis returned containing the correspondingInterruptedException.- Returns:
- this
Futureinstance
-
await
Blocks the current thread until thisFutureis completed, or returns immediately if it is already completed.If the current thread is interrupted while waiting, a failed
Futureis returned containing the correspondingInterruptedException.If the specified timeout is reached before completion, a failed
Futureis returned containing aTimeoutException.- Parameters:
timeout- the maximum time to waitunit- the time unit of the timeout argument- Returns:
- this
Futureinstance - Throws:
IllegalArgumentException- iftimeoutis negativeNullPointerException- ifunitis null
-
cancel
default boolean cancel()Cancels thisFuture. If it is running, the executing thread is interrupted.If the future is successfully cancelled, its result becomes a
Failure(CancellationException).- Returns:
falseif thisFutureis already completed or could not be cancelled,trueotherwise- Throws:
SecurityException- if the current thread is not permitted to modify the Future's thread- See Also:
-
cancel
boolean cancel(boolean mayInterruptIfRunning) Cancels thisFuture. A pending future may be interrupted depending on the underlyingExecutor.If the future is successfully cancelled, its result becomes a
Failure(CancellationException).- Parameters:
mayInterruptIfRunning-trueif a running thread should be interrupted;falseallows it to complete- Returns:
falseif thisFutureis already completed or could not be cancelled,trueotherwise- Throws:
SecurityException- if the current thread is not permitted to modify the Future's thread- See Also:
-
collect
Applies apartialFunctionto the value of thisFuture, collecting results only for values where the function is defined. The mapped result is wrapped in a newFuture.Example:
if (partialFunction.isDefinedAt(value)) { R newValue = partialFunction.apply(value); }- Type Parameters:
R- the type of the mapped result- Parameters:
partialFunction- a function that may not be defined for every value of this future- Returns:
- a new
Futurecontaining the mapped value - Throws:
NullPointerException- ifpartialFunctionis null
-
executor
-
executorService
Deprecated.Removed starting with Vavr 0.10.0, useexecutor()instead.This method is deprecated.THE DEFAULT IMPLEMENTATION (obtained by one of the
Futurefactory methods) MIGHT THROW ANUnsupportedOperationExceptionAT RUNTIME.- Returns:
- (never)
- Throws:
UnsupportedOperationException- if the underlyingExecutorisn't anExecutorService.
-
failed
Returns a projection that inverts the result of thisFuture.If this
Futuresucceeds, the resulting failed projection contains aNoSuchElementException.If this
Futurefails, the resulting failed projection succeeds with the exception as its value.- Returns:
- a new
Futurerepresenting the inverted result
-
fallbackTo
Returns aFuturethat yields the result of thisFutureif it succeeds. If thisFuturefails, the result of the giventhatFutureis returned if it succeeds. If bothFutures fail, the failure of thisFutureis returned.Example:
Future<Integer> future = Future.of(() -> { throw new Error(); }); Future<Integer> that = Future.of(() -> 1); Future<Integer> result = future.fallbackTo(that); // prints Success(1) result.onComplete(System.out::println);- Parameters:
that- a fallbackFutureto use if this one fails- Returns:
- a new
Futurerepresenting the result or fallback - Throws:
NullPointerException- ifthatis null
-
filter
Shortcut forfilterTry(predicate::test), filtering the result of thisFutureusing the given predicate.- Parameters:
predicate- a predicate to test the value of the future- Returns:
- a new
Futurecontaining the value if the predicate passes, or a failure otherwise - Throws:
NullPointerException- ifpredicateis null
-
filterTry
Filters the result of thisFutureusing the givenCheckedPredicate, delegating toTry.filterTry(CheckedPredicate).- Parameters:
predicate- a checked predicate to test the value of the future- Returns:
- a new
Futurecontaining the value if the predicate passes, or a failure otherwise - Throws:
NullPointerException- ifpredicateis null
-
getCause
Returns the underlying exception. This is syntactic sugar forfuture.getValue().map(Try::getCause).- Returns:
Noneif theFutureis not yet completed, orSome(Throwable)if it completed with a failure- Throws:
UnsupportedOperationException- if theFuturecompleted successfully with a value
-
getValue
-
isCancelled
boolean isCancelled()Checks whether thisFuturewas cancelled, i.e., its computation was interrupted before completion.- Returns:
trueif the computation was cancelled,falseotherwise
-
isCompleted
boolean isCompleted()Checks whether thisFutureis completed, i.e., whether it has finished with a value, failed, or was cancelled.- Returns:
trueif the computation has completed in any state,falseotherwise
-
isSuccess
default boolean isSuccess()Checks whether thisFuturecompleted successfully.- Returns:
trueif thisFuturehas completed with a successful result,falseotherwise
-
isFailure
default boolean isFailure()Checks whether thisFuturecompleted with a failure.- Returns:
trueif thisFuturehas completed with a failure,falseotherwise
-
onComplete
-
onFailure
Performs the given action once thisFutureis complete and its result is aTry.Failure.Note that a cancelled
Futureis also considered a failure.- Parameters:
action- an action to execute when this future fails- Returns:
- this
Future - Throws:
NullPointerException- ifactionis null
-
onSuccess
Performs the given action once thisFutureis complete and its result is aTry.Success.- Parameters:
action- an action to execute when this future succeeds- Returns:
- this
Future - Throws:
NullPointerException- ifactionis null
-
recover
Handles a failure of thisFutureby mapping the exception to a new result.Example:
// = "oh!" Future.of(() -> { throw new Error("oh!"); }) .recover(Throwable::getMessage);- Parameters:
f- a function that maps the failure exception to a new value- Returns:
- a new
Futurecontaining either the original success or the recovered value - Throws:
NullPointerException- iffis null
-
recoverWith
default Future<T> recoverWith(@NonNull Function<? super Throwable, ? extends Future<? extends T>> f) Handles a failure of thisFutureby returning the result of anotherFuture.Example:
// = "oh!" Future.of(() -> { throw new Error("oh!"); }) .recoverWith(ex -> Future.of(() -> ex.getMessage()));- Parameters:
f- a function that maps the failure exception to a newFuture- Returns:
- a new
Futurecontaining either the original success or the result of the recoveredFuture - Throws:
NullPointerException- iffis null
-
transform
Transforms the result of thisFutureusing the given function.- Type Parameters:
U- the type of the transformed result- Parameters:
f- a function to transform the result- Returns:
- a new
Futurecontaining the transformed result - Throws:
NullPointerException- iffis null
-
transformValue
default <U> Future<U> transformValue(@NonNull Function<? super Try<T>, ? extends Try<? extends U>> f) Transforms the value of thisFuture, regardless of whether it completed successfully or with a failure.- Type Parameters:
U- the type of the transformedTryresult- Parameters:
f- a function to transform theTryresult- Returns:
- a new
Futurecontaining the transformed result - Throws:
NullPointerException- iffis null
-
zip
Combines thisFuturewith anotherFuture, returning aFutureof a tuple of both results.If this
Futurefails, the resultingFuturecontains this failure. Otherwise, it contains the failure ofthatFuture, or a tuple of both successful results if both succeed.- Type Parameters:
U- the result type ofthat- Parameters:
that- anotherFutureto combine with- Returns:
- a new
Futurecontaining either a failure or a tuple of both results - Throws:
NullPointerException- ifthatis null
-
zipWith
default <U,R> Future<R> zipWith(@NonNull Future<? extends U> that, @NonNull BiFunction<? super T, ? super U, ? extends R> combinator) Combines thisFuturewith anotherFutureusing the given combinator function.If this
Futurefails, the resultingFuturecontains this failure. Otherwise, it contains the failure ofthatFuture, or the result of applying the combinator function to both successful results.- Type Parameters:
U- the result type ofthatR- the result type of the combined value- Parameters:
that- anotherFutureto combine withcombinator- a function to combine the successful results of both futures- Returns:
- a new
Futurecontaining either a failure or the combined result - Throws:
NullPointerException- ifthatorcombinatoris null
-
flatMap
Transforms the value of thisFutureusing the givenFunctionif it completes successfully, or returns aFuturewith the failure if thisFuturefails.This is a shortcut for
flatMapTry(CheckedFunction1).- Type Parameters:
U- the type of the resultingFuture- Parameters:
mapper- a function mapping the value to anotherFuture- Returns:
- a new
Futureresulting from applying the mapper, or aFuturewith the failure if thisFuturefails - Throws:
NullPointerException- ifmapperisnull
-
flatMapTry
default <U> Future<U> flatMapTry(@NonNull CheckedFunction1<? super T, ? extends Future<? extends U>> mapper) Transforms the value of thisFutureusing the givenCheckedFunction1if it completes successfully, or returns aFuturewith the failure if thisFuturefails.If applying the mapper throws an exception, a
Futurecontaining the exception is returned.- Type Parameters:
U- the type of the resultingFuture- Parameters:
mapper- a checked function mapping the value to anotherFuture- Returns:
- a new
Futureresulting from applying the mapper, or aFuturewith the failure if thisFuturefails - Throws:
NullPointerException- ifmapperisnull
-
forEach
Performs the givenactionasynchronously when thisFuturecompletes successfully.The
actionis not executed if theFuturecompletes with a failure. -
get
Returns the value of thisFutureif it completed successfully, or throws the underlying exception if it completed with a failure. Blocks the current thread if the computation is not yet finished.Note: If the computation failed, the underlying
Throwablecause is thrown. -
isAsync
-
isEmpty
-
isLazy
-
isSingleValued
default boolean isSingleValued()AFutureis single-valued.- Specified by:
isSingleValuedin interfaceValue<T>- Returns:
true
-
iterator
-
map
Description copied from interface:ValueMaps the underlying value to a different component type. -
mapTo
-
mapToVoid
-
mapTry
Maps the value of thisFutureto a new value using the givenCheckedFunction1if it completes successfully.If applying the mapper throws an exception, a
Futurecontaining the exception is returned.Example:
Future.of(() -> 0) .mapTry(x -> 1 / x); // division by zero will result in a failed Future- Type Parameters:
U- the type of the result- Parameters:
mapper- a checked function to apply to the value- Returns:
- a new
Futurecontaining the mapped value if thisFuturecompletes successfully, otherwise aFuturewith the failure - Throws:
NullPointerException- ifmapperisnull
-
orElse
Returns thisFutureif it completes successfully, or the given alternativeFutureif thisFuturefails.- Parameters:
other- the alternativeFutureto return if thisFuturefails- Returns:
- this
Futureif it completes successfully, otherwiseother - Throws:
NullPointerException- ifotheris null
-
orElse
Returns thisFutureif it completes successfully, or aFuturesupplied by the givenSupplierif thisFuturefails.The supplier is only invoked if this
Futurefails.- Parameters:
supplier- a supplier of an alternativeFuture- Returns:
- this
Futureif it completes successfully, otherwise theFuturereturned bysupplier - Throws:
NullPointerException- ifsupplieris null
-
peek
Description copied from interface:ValuePerforms the givenactionon the first element if this is an eager implementation. Performs the givenactionon all elements (the first immediately, successive deferred), if this is a lazy implementation. -
stringPrefix
Description copied from interface:ValueReturns the name of this Value type, which is used by toString().- Specified by:
stringPrefixin interfaceValue<T>- Returns:
- This type name.
-
executor()instead.