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 Executor
The default executor isForkJoinPool.commonPool()
.static final ExecutorService
Deprecated.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 boolean
cancel()
Cancels the Future.boolean
cancel
(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 givenpartialFunction
by mapping the value to typeR
.default Executor
executor()
Returns theExecutor
used 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 thisFuture
by callingTry.filterTry(CheckedPredicate)
.Returns aFuture
that eventually succeeds with the first result of the givenFuture
s which matches the givenpredicate
.find
(Executor executor, Iterable<? extends Future<? extends T>> futures, Predicate<? super T> predicate) Returns aFuture
that eventually succeeds with the first result of the givenFuture
s which matches the givenpredicate
.static <T> Future
<T> firstCompletedOf
(Iterable<? extends Future<? extends T>> futures) Returns a newFuture
that 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 newFuture
that 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 void
Performs the givenaction
asynchronously 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 aFuture
with the given java.util.concurrent.Future, backed by givenExecutor
static <T> Future
<T> fromJavaFuture
(Future<T> future) Creates aFuture
with the given java.util.concurrent.Future, backed by theDEFAULT_EXECUTOR
static <T> Future
<T> static <T> Future
<T> default T
get()
Gets the value if the computation result is aSuccess
or 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 boolean
isAsync()
AFutures
's value is computed asynchronously.boolean
Checks if this Future is cancelled, i.e.boolean
Checks if this Future is completed, i.e.default boolean
isEmpty()
Checks, if this future has a value.default boolean
Checks if this Future completed with a failure.default boolean
isLazy()
AFuture
's value is computed eagerly.default boolean
AFuture
is single-valued.default boolean
Checks 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 givenaction
on 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 manyFuture
s into a singleFuture
by transforming anIterable<Future<? extends T>>
into aFuture<Seq<T>>
.Reduces manyFuture
s into a singleFuture
by transforming anIterable<Future<? extends T>>
into aFuture<Seq<T>>
.default String
Returns 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 aCompletableFuture
default <U> U
Transforms 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 singleFuture
by 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 singleFuture
by 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 io.vavr.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 aFuture
that eventually succeeds with the first result of the givenFuture
s which matches the givenpredicate
. If no result matches, theFuture
will containOption.None
.The returned
Future
is 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
Option
of the first result of the givenfutures
that 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 aFuture
that eventually succeeds with the first result of the givenFuture
s which matches the givenpredicate
. If no result matches, theFuture
will containOption.None
.The returned
Future
is 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
Option
of the first result of the givenfutures
that satisfies the givenpredicate
. - Throws:
NullPointerException
- if one of the arguments is null
-
firstCompletedOf
Returns a newFuture
that 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 newFuture
that 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
Future
is 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
Future
that 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
Future
is 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
Future
that will contain the fold result. - Throws:
NullPointerException
- if executor, futures or f is null.
-
fromJavaFuture
Creates aFuture
with the given java.util.concurrent.Future, backed by theDEFAULT_EXECUTOR
- Type Parameters:
T
- Result type of the Future- Parameters:
future
- AFuture
- Returns:
- A new
Future
wrapping the result of the Java future - Throws:
NullPointerException
- if future is null
-
fromJavaFuture
Creates aFuture
with 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
Future
wrapping 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
Future
wrapping 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
Future
wrapping 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
Future
which contains either aSuccess
or 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
Future
which contains either aSuccess
or 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
future
instance 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 givencomputation
using a completion handler:
TheCheckedConsumer<Predicate<Try<T>>> computation = complete -> { // computation };
computation
is executed synchronously. It requires to complete the returned Future. A common use-case is to hand over thecomplete
predicate to anotherFuture
in 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
, namedcomplete
by 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
complete
will return true, successive calls will return false.- Type Parameters:
T
- Type of the result- Parameters:
task
- A computational task- Returns:
- a new
Future
instance
-
run
Deprecated.Experimental APICreates a (possibly blocking) Future that runs the results of the givencomputation
using a completion handler:
TheCheckedConsumer<Predicate<Try<T>>> computation = complete -> { // computation };
computation
is executed synchronously. It requires to complete the returned Future. A common use-case is to hand over thecomplete
predicate to anotherFuture
in 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
, namedcomplete
by 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
complete
will return true, successive calls will return false.- Type Parameters:
T
- Type of the result- Parameters:
executor
- AnExecutor
that runs the givencomputation
task
- A computational task- Returns:
- a new
Future
instance
-
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
Future
is 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
Future
that 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
Future
is 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
Future
that 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 manyFuture
s into a singleFuture
by transforming anIterable<Future<? extends T>>
into aFuture<Seq<T>>
.The resulting
Future
is 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
- AnIterable
ofFuture
s.- Returns:
- A
Future
of aSeq
of 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 manyFuture
s into a singleFuture
by transforming anIterable<Future<? extends T>>
into aFuture<Seq<T>>
.The resulting
Future
is backed by the givenExecutor
.- Type Parameters:
T
- Result type of the futures.- Parameters:
executor
- AnExecutor
.futures
- AnIterable
ofFuture
s.- Returns:
- A
Future
of aSeq
of 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:Value
Converts this to aCompletableFuture
- Specified by:
toCompletableFuture
in interfaceValue<T>
- Returns:
- A new
CompletableFuture
containing 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 singleFuture
by transforming anIterable<? extends T>
into aFuture<Seq<U>>
.The resulting
Future
is backed by theDEFAULT_EXECUTOR
.- Type Parameters:
T
- The type of the given values.U
- The mapped value type.- Parameters:
values
- AnIterable
ofFuture
s.mapper
- A mapper of values to Futures- Returns:
- A
Future
of aSeq
of 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 singleFuture
by transforming anIterable<? extends T>
into aFuture<Seq<U>>
.The resulting
Future
is backed by the givenExecutor
.- Type Parameters:
T
- The type of the given values.U
- The mapped value type.- Parameters:
executor
- AnExecutor
.values
- AnIterable
of values.mapper
- A mapper of values to Futures- Returns:
- A
Future
of aSeq
of 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
Future
is returned containing the correspondingInterruptedException
.- Returns:
- this
Future
instance
-
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
Future
is returned containing the correspondingInterruptedException
.If the deadline wasn't met, a failed
Future
is returned containing aTimeoutException
.- Parameters:
timeout
- the maximum time to waitunit
- the time unit of the timeout argument- Returns:
- this
Future
instance - Throws:
IllegalArgumentException
- iftimeout
is negativeNullPointerException
- ifunit
is 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 thisFuture
is 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
-true
if a running thread should be interrupted, otherwise a running thread is allowed to complete its computation.- Returns:
false
, if thisFuture
is 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 givenpartialFunction
by mapping the value to typeR
.
If the element makes it through that filter, the mapped instance is wrapped inpartialFunction.isDefinedAt(value)
Future
R 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
Future
instance containing value of typeR
- Throws:
NullPointerException
- ifpartialFunction
is null
-
executor
Returns theExecutor
used by thisFuture
.- Returns:
- The underlying
Executor
.
-
executorService
Deprecated.Removed starting with Vavr 0.10.0, useexecutor()
instead.This method is deprecated.THE DEFAULT IMPLEMENTATION (obtained by one of the
Future
factory methods) MIGHT THROW ANUnsupportedOperationException
AT RUNTIME.- Returns:
- (never)
- Throws:
UnsupportedOperationException
- if the underlyingExecutor
isn'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 ofthat
Future 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
- ifpredicate
is null
-
filterTry
Filters the result of thisFuture
by callingTry.filterTry(CheckedPredicate)
.- Parameters:
predicate
- A checked predicate- Returns:
- A new
Future
- Throws:
NullPointerException
- ifpredicate
is 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
Returns the value of the Future.- Returns:
None
, if the Future is not yet completed or was cancelled, otherwiseSome(Try)
.
-
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
Performs the action once the Future is complete.- Parameters:
action
- An action to be performed when this future is complete.- Returns:
- this Future
- Throws:
NullPointerException
- ifaction
is null.
-
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
- ifaction
is 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
- ifaction
is 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
- iff
is 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
- iff
is null
-
transform
Transforms thisFuture
.- Type Parameters:
U
- Type of transformation result- Parameters:
f
- A transformation- Returns:
- An instance of type
U
- Throws:
NullPointerException
- iff
is null
-
transformValue
Transforms the value of thisFuture
, whether it is a success or a failure.- Type Parameters:
U
- Generic type of transformationTry
result- Parameters:
f
- A transformation- Returns:
- A
Future
of typeU
- Throws:
NullPointerException
- iff
is 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
- ifthat
is 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 ofthat
R
- Result type off
- Parameters:
that
- Another Futurecombinator
- The combinator function- Returns:
- A new Future that returns both Future results.
- Throws:
NullPointerException
- ifthat
is null
-
flatMap
-
flatMapTry
-
forEach
Performs the givenaction
asynchronously hence this Future result becomes available. Theaction
is not performed, if the result is a failure. -
get
Gets the value if the computation result is aSuccess
or 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 underlyingcause
of typeThrowable
is thrown. -
isAsync
default boolean isAsync()AFutures
's value is computed asynchronously. -
isEmpty
default boolean isEmpty()Checks, if this future has a value. -
isLazy
default boolean isLazy()AFuture
's value is computed eagerly. -
isSingleValued
default boolean isSingleValued()AFuture
is single-valued.- Specified by:
isSingleValued
in interfaceValue<T>
- Returns:
true
-
iterator
Description copied from interface:Value
Returns a richio.vavr.collection.Iterator
. -
map
Description copied from interface:Value
Maps the underlying value to a different component type. -
mapTry
-
orElse
-
orElse
-
peek
Description copied from interface:Value
Performs the givenaction
on the first element if this is an eager implementation. Performs the givenaction
on all elements (the first immediately, successive deferred), if this is a lazy implementation. -
stringPrefix
Description copied from interface:Value
Returns the name of this Value type, which is used by toString().- Specified by:
stringPrefix
in interfaceValue<T>
- Returns:
- This type name.
-