Interface Future<T>
- Type Parameters:
T- Type of the computation result.
- All Known Implementing Classes:
FutureImpl
The underlying Executor is used to execute asynchronous handlers, e.g. via
onComplete(...).
A Future has two states: pending and completed.
- Pending: The computation is ongoing. Only a pending future may be completed or cancelled.
- Completed: The computation finished successfully with a result, failed with an exception or was cancelled.
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final ExecutorThe default executor isForkJoinPool.commonPool().static final ExecutorServiceDeprecated.Will be removed in Vavr 1.0. -
Method Summary
Modifier and TypeMethodDescriptionSupport for chaining of callbacks that are guaranteed to be executed in a specific order.await()Blocks the current Thread until this Future completed or returns immediately if this Future is already completed.Blocks the current Thread until this Future completed or returns immediately if this Future is already completed.default booleancancel()Cancels the Future.booleancancel(boolean mayInterruptIfRunning) Cancels the Future.default <R> Future<R> collect(PartialFunction<? super T, ? extends R> partialFunction) Collects value that is in the domain of the givenpartialFunctionby mapping the value to typeR.default Executorexecutor()Returns theExecutorused by thisFuture.Deprecated.Removed starting with Vavr 0.10.0, useexecutor()instead.failed()A projection that inverses the result of this Future.static <T> Future<T> static <T> Future<T> fallbackTo(Future<? extends T> that) Returns a Future that returns the result of this Future, if it is a success.Shortcut forfilterTry(predicate::test.filterTry(CheckedPredicate<? super T> predicate) Filters the result of thisFutureby callingTry.filterTry(CheckedPredicate).Returns aFuturethat eventually succeeds with the first result of the givenFutures which matches the givenpredicate.find(Executor executor, Iterable<? extends Future<? extends T>> futures, Predicate<? super T> predicate) Returns aFuturethat eventually succeeds with the first result of the givenFutures which matches the givenpredicate.static <T> Future<T> firstCompletedOf(Iterable<? extends Future<? extends T>> futures) Returns a newFuturethat will contain the result of the first of the given futures that is completed, backed by theDEFAULT_EXECUTOR.static <T> Future<T> firstCompletedOf(Executor executor, Iterable<? extends Future<? extends T>> futures) Returns a newFuturethat will contain the result of the first of the given futures that is completed, backed by the givenExecutor.default <U> Future<U> default <U> Future<U> flatMapTry(CheckedFunction1<? super T, ? extends Future<? extends U>> mapper) static <T,U> Future <U> fold(Iterable<? extends Future<? extends T>> futures, U zero, BiFunction<? super U, ? super T, ? extends U> f) Returns a Future which contains the result of the fold of the given future values.static <T,U> Future <U> fold(Executor executor, Iterable<? extends Future<? extends T>> futures, U zero, BiFunction<? super U, ? super T, ? extends U> f) Returns a Future which contains the result of the fold of the given future values.default voidPerforms the givenactionasynchronously hence this Future result becomes available.static <T> Future<T> fromCompletableFuture(CompletableFuture<T> future) static <T> Future<T> fromCompletableFuture(Executor executor, CompletableFuture<T> future) static <T> Future<T> fromJavaFuture(Executor executor, Future<T> future) Creates aFuturewith the given java.util.concurrent.Future, backed by givenExecutorstatic <T> Future<T> fromJavaFuture(Future<T> future) Creates aFuturewith the given java.util.concurrent.Future, backed by theDEFAULT_EXECUTORstatic <T> Future<T> static <T> Future<T> default Tget()Gets the value if the computation result is aSuccessor throws if it was aFailure.getCause()Returns the underlying exception of this Future, syntactic sugar forfuture.getValue().map(Try::getCause).getValue()Returns the value of the Future.default booleanisAsync()AFutures's value is computed asynchronously.booleanChecks if this Future is cancelled, i.e.booleanChecks if this Future is completed, i.e.default booleanisEmpty()Checks, if this future has a value.default booleanChecks if this Future completed with a failure.default booleanisLazy()AFuture's value is computed eagerly.default booleanAFutureis single-valued.default booleanChecks if this Future completed with a success.iterator()Returns a richio.vavr.collection.Iterator.default <U> Future<U> Maps the underlying value to a different component type.default <U> Future<U> mapTry(CheckedFunction1<? super T, ? extends U> mapper) static <T> Future<T> Narrows a widenedFuture<? extends T>toFuture<T>by performing a type-safe cast.static <T> Future<T> of(CheckedFunction0<? extends T> computation) Starts an asynchronous computation, backed by theDEFAULT_EXECUTOR.static <T> Future<T> of(Executor executor, CheckedFunction0<? extends T> computation) Starts an asynchronous computation, backed by the givenExecutor.static <T> Future<T> ofCallable(Callable<? extends T> computation) Deprecated.Will be removed.static <T> Future<T> ofCallable(Executor executor, Callable<? extends T> computation) Deprecated.Will be removed.static <T> Future<T> ofSupplier(Executor executor, Supplier<? extends T> computation) Deprecated.Will be removed.static <T> Future<T> ofSupplier(Supplier<? extends T> computation) Deprecated.Will be removed.onComplete(Consumer<? super Try<T>> action) Performs the action once the Future is complete.Performs the action once the Future is complete and the result is aTry.Failure.Performs the action once the Future is complete and the result is aTry.Success.Performs the givenactionon the first element if this is an eager implementation.Handles a failure of this Future by returning another result.recoverWith(Function<? super Throwable, ? extends Future<? extends T>> f) Handles a failure of this Future by returning the result of another Future.static <T> Future<T> reduce(Iterable<? extends Future<? extends T>> futures, BiFunction<? super T, ? super T, ? extends T> f) Returns a Future which contains the reduce result of the given future values.static <T> Future<T> reduce(Executor executor, Iterable<? extends Future<? extends T>> futures, BiFunction<? super T, ? super T, ? extends T> f) Returns a Future which contains the reduce result of the given future values.run(CheckedRunnable unit) Runs an asynchronous computation, backed by theDEFAULT_EXECUTOR.static <T> Future<T> Deprecated.Experimental APIrun(Executor executor, CheckedRunnable unit) Starts an asynchronous computation, backed by the givenExecutor.static <T> Future<T> Deprecated.Experimental APIrunRunnable(Runnable computation) Deprecated.Will be removed.runRunnable(Executor executor, Runnable computation) Deprecated.Will be removed.Reduces manyFutures into a singleFutureby transforming anIterable<Future<? extends T>>into aFuture<Seq<T>>.Reduces manyFutures 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(Executor executor, T result) Creates a succeededFuture, backed by the givenExecutor.static <T> Future<T> successful(T result) Creates a succeededFuture, backed by theDEFAULT_EXECUTOR.default CompletableFuture<T> Converts this to aCompletableFuturedefault <U> UTransforms thisFuture.default <U> Future<U> transformValue(Function<? super Try<T>, ? extends Try<? extends U>> f) Transforms the value of thisFuture, whether it is a success or a failure.Maps the values of an iterable in parallel to a sequence of mapped values into a singleFutureby transforming anIterable<? extends T>into aFuture<Seq<U>>.traverse(Executor executor, Iterable<? extends T> values, Function<? super T, ? extends Future<? extends U>> mapper) Maps the values of an iterable in parallel to a sequence of mapped values into a singleFutureby transforming anIterable<? extends T>into aFuture<Seq<U>>.Returns a tuple of this and that Future result.default <U,R> Future <R> zipWith(Future<? extends U> that, BiFunction<? super T, ? super U, ? extends R> combinator) Returns a this and that Future result combined using a 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_SERVICE
Deprecated.Will be removed in Vavr 1.0. Useinstead.The default executor service 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:
-
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 value type of a successful result.- Parameters:
exception- The reason why it failed.- Returns:
- A failed
Future. - Throws:
NullPointerException- if exception is null
-
failed
- Type Parameters:
T- The value type of a successful result.- Parameters:
executor- AnExecutor.exception- The reason why it failed.- Returns:
- A failed
Future. - Throws:
NullPointerException- if executor or exception is null
-
find
static <T> Future<Option<T>> find(Iterable<? extends Future<? extends T>> futures, Predicate<? super T> predicate) Returns aFuturethat eventually succeeds with the first result of the givenFutures which matches the givenpredicate. If no result matches, theFuturewill containOption.None.The returned
Futureis backed by theDEFAULT_EXECUTOR.- Type Parameters:
T- Result type of the futures.- Parameters:
futures- An iterable of futures.predicate- A predicate that tests successful future results.- Returns:
- A Future of an
Optionof the first result of the givenfuturesthat satisfies the givenpredicate. - Throws:
NullPointerException- if one of the arguments is null
-
find
static <T> Future<Option<T>> find(Executor executor, Iterable<? extends Future<? extends T>> futures, Predicate<? super T> predicate) Returns aFuturethat eventually succeeds with the first result of the givenFutures which matches the givenpredicate. If no result matches, theFuturewill containOption.None.The returned
Futureis backed by the givenExecutor.- Type Parameters:
T- Result type of the futures.- Parameters:
executor- AnExecutor.futures- An iterable of futures.predicate- A predicate that tests successful future results.- Returns:
- A Future of an
Optionof the first result of the givenfuturesthat satisfies the givenpredicate. - Throws:
NullPointerException- if one of the arguments is null
-
firstCompletedOf
Returns a newFuturethat will contain the result of the first of the given futures that is completed, backed by theDEFAULT_EXECUTOR.- Type Parameters:
T- The result type.- Parameters:
futures- An iterable of futures.- Returns:
- A new
Future. - Throws:
NullPointerException- if futures is null
-
firstCompletedOf
static <T> Future<T> firstCompletedOf(Executor executor, Iterable<? extends Future<? extends T>> futures) Returns a newFuturethat will contain the result of the first of the given futures that is completed, backed by the givenExecutor.- Type Parameters:
T- The result type.- Parameters:
executor- AnExecutor.futures- An iterable of futures.- Returns:
- A new
Future. - Throws:
NullPointerException- if executor or futures is null
-
fold
static <T,U> Future<U> fold(Iterable<? extends Future<? extends T>> futures, U zero, BiFunction<? super U, ? super T, ? extends U> f) Returns a Future which contains the result of the fold of the given future values. If any future or the fold fail, the result is a failure.The resulting
Futureis backed by theDEFAULT_EXECUTOR.- Type Parameters:
T- The result type of the givenFutures.U- The fold result type.- Parameters:
futures- An iterable of futures.zero- The zero element of the fold.f- The fold operation.- Returns:
- A new
Futurethat will contain the fold result. - Throws:
NullPointerException- if futures or f is null.
-
fold
static <T,U> Future<U> fold(Executor executor, Iterable<? extends Future<? extends T>> futures, U zero, BiFunction<? super U, ? super T, ? extends U> f) Returns a Future which contains the result of the fold of the given future values. If any future or the fold fail, the result is a failure.The resulting
Futureis backed by the givenExecutor.- Type Parameters:
T- The result type of the givenFutures.U- The fold result type.- Parameters:
executor- AnExecutor.futures- An iterable of futures.zero- The zero element of the fold.f- The fold operation.- Returns:
- A new
Futurethat will contain the fold result. - Throws:
NullPointerException- if executor, futures or f is null.
-
fromJavaFuture
Creates aFuturewith the given java.util.concurrent.Future, backed by theDEFAULT_EXECUTOR- Type Parameters:
T- Result type of the Future- Parameters:
future- AFuture- Returns:
- A new
Futurewrapping the result of the Java future - Throws:
NullPointerException- if future is null
-
fromJavaFuture
Creates aFuturewith the given java.util.concurrent.Future, backed by givenExecutor- Type Parameters:
T- Result type of the Future- Parameters:
executor- AnExecutor.future- AFuture.- Returns:
- A new
Futurewrapping the result of the Java future - Throws:
NullPointerException- if executor or future is null
-
fromCompletableFuture
- Type Parameters:
T- Result type of the Future- Parameters:
future- ACompletableFuture- Returns:
- A new
Futurewrapping the result of theCompletableFuture - Throws:
NullPointerException- if future is null
-
fromCompletableFuture
@GwtIncompatible static <T> Future<T> fromCompletableFuture(Executor executor, CompletableFuture<T> future) - Type Parameters:
T- Result type of the Future- Parameters:
executor- AnExecutor.future- ACompletableFuture.- Returns:
- A new
Futurewrapping the result of theCompletableFuture - Throws:
NullPointerException- if executor or future is null
-
fromTry
- Type Parameters:
T- The value type of a successful result.- Parameters:
result- The result.- Returns:
- A completed
Futurewhich contains either aSuccessor aFailure. - Throws:
NullPointerException- if result is null
-
fromTry
- Type Parameters:
T- The value type of a successful result.- Parameters:
executor- AnExecutor.result- The result.- Returns:
- A completed
Futurewhich contains either aSuccessor aFailure. - Throws:
NullPointerException- if executor or result is null
-
narrow
Narrows a widenedFuture<? extends T>toFuture<T>by performing a type-safe cast. This is eligible because immutable/read-only collections are covariant.- Type Parameters:
T- Component type of theFuture.- Parameters:
future- AFuture.- Returns:
- the given
futureinstance as narrowed typeFuture<T>.
-
ofSupplier
Deprecated.Will be removed. UseFuture.of(supplier::get)instead ofFuture.ofSupplier(supplier).Starts an asynchronous computation, backed by theDEFAULT_EXECUTOR.- Type Parameters:
T- Type of the computation result.- Parameters:
computation- A computation.- Returns:
- A new Future instance
- Throws:
NullPointerException- if computation is null.
-
ofSupplier
Deprecated.Will be removed. UseFuture.of(executor, supplier::get)instead ofFuture.ofSupplier(executor, supplier).Starts an asynchronous computation, backed by the givenExecutor.- Type Parameters:
T- Type of the computation result.- Parameters:
executor- An executor service.computation- A computation.- Returns:
- A new Future instance
- Throws:
NullPointerException- if one of executor or computation is null.
-
ofCallable
Deprecated.Will be removed. UseFuture.of(callable::call)instead ofFuture.ofCallable(callable).Starts an asynchronous computation, backed by theDEFAULT_EXECUTOR.- Type Parameters:
T- Type of the computation result.- Parameters:
computation- A computation- Returns:
- A new Future instance
- Throws:
NullPointerException- if computation is null.
-
ofCallable
Deprecated.Will be removed. UseFuture.of(executor, callable::call)instead ofFuture.ofCallable(executor, callable).Starts an asynchronous computation, backed by the givenExecutor.- Type Parameters:
T- Type of the computation result.- Parameters:
executor- An executor service.computation- A computation.- Returns:
- A new Future instance
- Throws:
NullPointerException- if one of executor or computation is null.
-
runRunnable
Deprecated.Will be removed. UseFuture.of(runnable::run)instead ofFuture.runRunnable(runnable).Starts an asynchronous computation, backed by theDEFAULT_EXECUTOR.- Parameters:
computation- A computation- Returns:
- A new Future instance
- Throws:
NullPointerException- if computation is null.
-
runRunnable
Deprecated.Will be removed. UseFuture.of(executor, runnable::run)instead ofFuture.runRunnable(executor, runnable).Starts an asynchronous computation, backed by the givenExecutor.- Parameters:
executor- An executor service.computation- A computation.- Returns:
- A new Future instance
- Throws:
NullPointerException- if one of executor or computation is null.
-
of
Starts an asynchronous computation, backed by theDEFAULT_EXECUTOR.- Type Parameters:
T- Type of the computation result.- Parameters:
computation- A computation.- Returns:
- A new Future instance.
- Throws:
NullPointerException- if computation is null.
-
of
Starts an asynchronous computation, backed by the givenExecutor.- Type Parameters:
T- Type of the computation result.- Parameters:
executor- AnExecutor.computation- A computation.- Returns:
- A new Future instance.
- Throws:
NullPointerException- if one of executor or computation is null.
-
run
Deprecated.Experimental APICreates a (possibly blocking) Future that runs the results of the givencomputationusing a completion handler:
TheCheckedConsumer<Predicate<Try<T>>> computation = complete -> { // computation };computationis executed synchronously. It requires to complete the returned Future. A common use-case is to hand over thecompletepredicate to anotherFuturein order to prevent blocking:
The computation receives aFuture<String> greeting(Future<String> nameFuture) { return Future.run(complete -> { nameFuture.onComplete(name -> complete.test("Hi " + name)); }); }Predicate, namedcompleteby convention, that takes a result of typeTry<T>and returns a boolean that states whether the Future was completed.Future completion is an idempotent operation in the way that the first call of
completewill return true, successive calls will return false.- Type Parameters:
T- Type of the result- Parameters:
task- A computational task- Returns:
- a new
Futureinstance
-
run
Deprecated.Experimental APICreates a (possibly blocking) Future that runs the results of the givencomputationusing a completion handler:
TheCheckedConsumer<Predicate<Try<T>>> computation = complete -> { // computation };computationis executed synchronously. It requires to complete the returned Future. A common use-case is to hand over thecompletepredicate to anotherFuturein order to prevent blocking:
The computation receives aFuture<String> greeting(Future<String> nameFuture) { return Future.run(complete -> { nameFuture.onComplete(name -> complete.with("Hi " + name)); }); }Predicate, namedcompleteby convention, that takes a result of typeTry<T>and returns a boolean that states whether the Future was completed.Future completion is an idempotent operation in the way that the first call of
completewill return true, successive calls will return false.- Type Parameters:
T- Type of the result- Parameters:
executor- AnExecutorthat runs the givencomputationtask- A computational task- Returns:
- a new
Futureinstance
-
reduce
static <T> Future<T> reduce(Iterable<? extends Future<? extends T>> futures, BiFunction<? super T, ? super T, ? extends T> f) Returns a Future which contains the reduce result of the given future values. The zero is the result of the first future that completes. If any future or the reduce operation fail, the result is a failure.The resulting
Futureis backed by theDEFAULT_EXECUTOR.- Type Parameters:
T- The result type of the givenFutures.- Parameters:
futures- An iterable of futures.f- The reduce operation.- Returns:
- A new
Futurethat will contain the reduce result. - Throws:
NullPointerException- if executor, futures or f is null.
-
reduce
static <T> Future<T> reduce(Executor executor, Iterable<? extends Future<? extends T>> futures, BiFunction<? super T, ? super T, ? extends T> f) Returns a Future which contains the reduce result of the given future values. The zero is the result of the first future that completes. If any future or the reduce operation fail, the result is a failure.The resulting
Futureis backed by the givenExecutor.- Type Parameters:
T- The result type of the givenFutures.- Parameters:
executor- AnExecutor.futures- An iterable of futures.f- The reduce operation.- Returns:
- A new
Futurethat will contain the reduce result. - Throws:
NullPointerException- if executor, futures or f is null.
-
run
Runs an asynchronous computation, backed by theDEFAULT_EXECUTOR.- Parameters:
unit- A unit of work.- Returns:
- A new Future instance which results in nothing.
- Throws:
NullPointerException- if unit is null.
-
run
Starts an asynchronous computation, backed by the givenExecutor.- Parameters:
executor- AnExecutor.unit- A unit of work.- Returns:
- A new Future instance which results in nothing.
- Throws:
NullPointerException- if one of executor or unit is null.
-
sequence
Reduces manyFutures into a singleFutureby transforming anIterable<Future<? extends T>>into aFuture<Seq<T>>.The resulting
Futureis backed by theDEFAULT_EXECUTOR.-
If all of the given Futures succeed, sequence() succeeds too:
// = Future(Success(Seq(1, 2))) sequence( List.of( Future.of(() -> 1), Future.of(() -> 2) ) ); -
If a given Future fails, sequence() fails too:
// = Future(Failure(Error))) sequence( List.of( Future.of(() -> 1), Future.of(() -> { throw new Error(); } ) );
- Type Parameters:
T- Result type of the futures.- Parameters:
futures- AnIterableofFutures.- Returns:
- A
Futureof aSeqof results. - Throws:
NullPointerException- if futures is null.
-
If all of the given Futures succeed, sequence() succeeds too:
-
sequence
static <T> Future<Seq<T>> sequence(Executor executor, Iterable<? extends Future<? extends T>> futures) Reduces manyFutures into a singleFutureby transforming anIterable<Future<? extends T>>into aFuture<Seq<T>>.The resulting
Futureis backed by the givenExecutor.- Type Parameters:
T- Result type of the futures.- Parameters:
executor- AnExecutor.futures- AnIterableofFutures.- Returns:
- A
Futureof aSeqof results. - Throws:
NullPointerException- if executor or futures is null.
-
successful
Creates a succeededFuture, backed by theDEFAULT_EXECUTOR.- Type Parameters:
T- The value type of a successful result.- Parameters:
result- The result.- Returns:
- A succeeded
Future.
-
successful
Creates a succeededFuture, backed by the givenExecutor.- Type Parameters:
T- The value type of a successful result.- Parameters:
executor- AnExecutor.result- The result.- Returns:
- A succeeded
Future. - Throws:
NullPointerException- if executor is 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(Iterable<? extends T> values, Function<? super T, ? extends Future<? extends U>> mapper) Maps the values of an iterable in parallel to a sequence of mapped values into a singleFutureby transforming anIterable<? extends T>into aFuture<Seq<U>>.The resulting
Futureis backed by theDEFAULT_EXECUTOR.- Type Parameters:
T- The type of the given values.U- The mapped value type.- Parameters:
values- AnIterableofFutures.mapper- A mapper of values to Futures- Returns:
- A
Futureof aSeqof results. - Throws:
NullPointerException- if values or f is null.
-
traverse
static <T,U> Future<Seq<U>> traverse(Executor executor, Iterable<? extends T> values, Function<? super T, ? extends Future<? extends U>> mapper) Maps the values of an iterable in parallel to a sequence of mapped values into a singleFutureby transforming anIterable<? extends T>into aFuture<Seq<U>>.The resulting
Futureis backed by the givenExecutor.- Type Parameters:
T- The type of the given values.U- The mapped value type.- Parameters:
executor- AnExecutor.values- AnIterableof values.mapper- A mapper of values to Futures- Returns:
- A
Futureof aSeqof results. - Throws:
NullPointerException- if executor, values or f is null.
-
andThen
Support for chaining of callbacks that are guaranteed to be executed in a specific order.An exception, which occurs when performing the given
action, is not propagated to the outside. In other words, subsequent actions are performed based on the value of the original Future.Example:
// prints Success(1) Future.of(() -> 1) .andThen(t -> { throw new Error(""); }) .andThen(System.out::println);- Parameters:
action- A side-effecting action.- Returns:
- A new Future that contains this result and which is completed after the given action was performed.
- Throws:
NullPointerException- if action is null
-
await
Blocks the current Thread until this Future completed or returns immediately if this Future is already completed.In the case the current thread was interrupted while waiting, a failed
Futureis returned containing the correspondingInterruptedException.- Returns:
- this
Futureinstance
-
await
Blocks the current Thread until this Future completed or returns immediately if this Future is already completed.In the case the current thread was interrupted while waiting, a failed
Futureis returned containing the correspondingInterruptedException.If the deadline wasn't met, 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 the Future. A running thread is interrupted.If the Future was successfully cancelled, the result is a
Failure(CancellationException).- Returns:
false, if thisFutureis already completed or could not be cancelled, otherwisetrue.- Throws:
SecurityException- if the current thread cannot modify the Future's thread- See Also:
-
cancel
boolean cancel(boolean mayInterruptIfRunning) Cancels the Future. A pending Future may be interrupted, depending on the underlyingExecutor.If the Future was successfully cancelled, the result is a
Failure(CancellationException).- Parameters:
mayInterruptIfRunning-trueif a running thread should be interrupted, otherwise a running thread is allowed to complete its computation.- Returns:
false, if thisFutureis already completed or could not be cancelled, otherwisetrue.- Throws:
SecurityException- if the current thread cannot modify the Future's thread- See Also:
-
collect
Collects value that is in the domain of the givenpartialFunctionby mapping the value to typeR.
If the element makes it through that filter, the mapped instance is wrapped inpartialFunction.isDefinedAt(value)FutureR newValue = partialFunction.apply(value)- Type Parameters:
R- The new value type- Parameters:
partialFunction- A function that is not necessarily defined on value of this future.- Returns:
- A new
Futureinstance containing value of typeR - 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
A projection that inverses the result of this Future.If this Future succeeds, the failed projection returns a failure containing a
NoSuchElementException.If this Future fails, the failed projection returns a success containing the exception.
- Returns:
- A new Future which contains an exception at a point of time.
-
fallbackTo
Returns a Future that returns the result of this Future, if it is a success. If the value of this Future is a failure, the result ofthatFuture is returned, if that is a success. If both Futures fail, the failure of this Future is returned.Example:
Future<Integer> future = Future.of(() -> { throw new Error(); }); Future<Integer> that = Future.of(() -> 1); Future<Integer> result = future.fallbackTo(that); // prints Some(1) result.onComplete(System.out::println);- Parameters:
that- A fallback future computation- Returns:
- A new Future
- Throws:
NullPointerException- if that is null
-
filter
Shortcut forfilterTry(predicate::test.- Parameters:
predicate- A predicate- Returns:
- A new
Future - Throws:
NullPointerException- ifpredicateis null
-
filterTry
Filters the result of thisFutureby callingTry.filterTry(CheckedPredicate).- Parameters:
predicate- A checked predicate- Returns:
- A new
Future - Throws:
NullPointerException- ifpredicateis null
-
getCause
Returns the underlying exception of this Future, syntactic sugar forfuture.getValue().map(Try::getCause).- Returns:
- None if the Future is not completed yet. Returns Some(Throwable) if the Future was completed with a failure.
- Throws:
UnsupportedOperationException- if the Future was successfully completed with a value
-
getValue
-
isCancelled
boolean isCancelled()Checks if this Future is cancelled, i.e. the thread was forced to stop before completion.- Returns:
- true, if the computation was cancelled, false otherwise
-
isCompleted
boolean isCompleted()Checks if this Future is completed, i.e. has a value.- Returns:
- true, if the computation successfully finished, failed or was cancelled, false otherwise.
-
isSuccess
default boolean isSuccess()Checks if this Future completed with a success.- Returns:
- true, if this Future completed and is a Success, false otherwise.
-
isFailure
default boolean isFailure()Checks if this Future completed with a failure.- Returns:
- true, if this Future completed and is a Failure, false otherwise.
-
onComplete
-
onFailure
Performs the action once the Future is complete and the result is aTry.Failure. Please note that the future is also a failure when it was cancelled.- Parameters:
action- An action to be performed when this future failed.- Returns:
- this Future
- Throws:
NullPointerException- ifactionis null.
-
onSuccess
Performs the action once the Future is complete and the result is aTry.Success.- Parameters:
action- An action to be performed when this future succeeded.- Returns:
- this Future
- Throws:
NullPointerException- ifactionis null.
-
recover
Handles a failure of this Future by returning another result.Example:
// = "oh!" Future.of(() -> new Error("oh!")).recover(Throwable::getMessage);- Parameters:
f- A function which takes the exception of a failure and returns a new value.- Returns:
- A new Future.
- Throws:
NullPointerException- iffis null
-
recoverWith
Handles a failure of this Future by returning the result of another Future.Example:
// = "oh!" Future.of(() -> { throw new Error("oh!"); }).recoverWith(x -> Future.of(x::getMessage));- Parameters:
f- A function which takes the exception of a failure and returns a new future.- Returns:
- A new Future.
- Throws:
NullPointerException- iffis null
-
transform
Transforms thisFuture.- Type Parameters:
U- Type of transformation result- Parameters:
f- A transformation- Returns:
- An instance of type
U - Throws:
NullPointerException- iffis null
-
transformValue
Transforms the value of thisFuture, whether it is a success or a failure.- Type Parameters:
U- Generic type of transformationTryresult- Parameters:
f- A transformation- Returns:
- A
Futureof typeU - Throws:
NullPointerException- iffis null
-
zip
Returns a tuple of this and that Future result.If this Future failed the result contains this failure. Otherwise the result contains that failure or a tuple of both successful Future results.
- Type Parameters:
U- Result type ofthat- Parameters:
that- Another Future- Returns:
- A new Future that returns both Future results.
- Throws:
NullPointerException- ifthatis null
-
zipWith
default <U,R> Future<R> zipWith(Future<? extends U> that, BiFunction<? super T, ? super U, ? extends R> combinator) Returns a this and that Future result combined using a given combinator function.If this Future failed the result contains this failure. Otherwise the result contains that failure or a combination of both successful Future results.
- Type Parameters:
U- Result type ofthatR- Result type off- Parameters:
that- Another Futurecombinator- The combinator function- Returns:
- A new Future that returns both Future results.
- Throws:
NullPointerException- ifthatis null
-
flatMap
-
flatMapTry
-
forEach
Performs the givenactionasynchronously hence this Future result becomes available. Theactionis not performed, if the result is a failure. -
get
Gets the value if the computation result is aSuccessor throws if it was aFailure. Waits for the result if necessary by blocking the current thread.IMPORTANT! If the computation result is a
Try.Failure, the underlyingcauseof typeThrowableis thrown. -
isAsync
-
isEmpty
-
isLazy
-
isSingleValued
default boolean isSingleValued()AFutureis single-valued.- Specified by:
isSingleValuedin interfaceValue<T>- Returns:
true
-
iterator
-
map
-
mapTry
-
orElse
-
orElse
-
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.
-