Interface Future<T>
-
- Type Parameters:
T- the type of the computation result
- All Superinterfaces:
java.lang.Iterable<T>,Value<T>
- All Known Implementing Classes:
FutureImpl
public interface Future<T> extends Value<T>
Represents the result of an asynchronous computation that becomes available at some point in the future. All operations provided by thisFutureare non-blocking.The underlying
Executoris used to execute asynchronous handlers, for example viaonComplete(...).A
Futurehas 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
Futureat any time. These callbacks are executed as soon as theFuturecompletes. If a callback is registered on a completedFuture, it is executed immediately. Execution may occur on a separate thread, depending on the underlyingExecutor. Callbacks registered on a cancelledFutureare executed with the failed result.
-
-
Field Summary
Fields Modifier and Type Field Description static java.util.concurrent.ExecutorDEFAULT_EXECUTORThe default executor isForkJoinPool.commonPool().
-
Method Summary
All Methods Static Methods Instance Methods Abstract Methods Default Methods Deprecated Methods Modifier and Type Method Description default Future<T>andThen(@NonNull java.util.function.Consumer<? super Try<T>> action)Supports chaining of callbacks that are guaranteed to be executed in order.Future<T>await()Blocks the current thread until thisFutureis completed, or returns immediately if it is already completed.Future<T>await(long timeout, java.util.concurrent.TimeUnit unit)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 java.util.concurrent.Executorexecutor()Returns theExecutorthat executes asynchronous handlers for thisFuture.java.util.concurrent.ExecutorServiceexecutorService()Deprecated.Removed starting with Vavr 0.10.0, useexecutor()instead.default Future<java.lang.Throwable>failed()Returns a projection that inverts the result of thisFuture.static <T> Future<T>failed(@NonNull java.lang.Throwable exception)static <T> Future<T>failed(@NonNull java.util.concurrent.Executor executor, @NonNull java.lang.Throwable exception)Creates a failedFuturewith the givenexception, executing callbacks using the specifiedExecutor.default Future<T>fallbackTo(@NonNull Future<? extends T> that)Returns aFuturethat yields the result of thisFutureif it succeeds.default Future<T>filter(@NonNull java.util.function.Predicate<? super T> predicate)Shortcut forfilterTry(predicate::test), filtering the result of thisFutureusing the given predicate.default Future<T>filterTry(@NonNull CheckedPredicate<? super T> predicate)Filters the result of thisFutureusing the givenCheckedPredicate, delegating toTry.filterTry(CheckedPredicate).static <T> Future<Option<T>>find(@NonNull java.lang.Iterable<? extends Future<? extends T>> futures, @NonNull java.util.function.Predicate<? super T> predicate)Returns aFuturethat completes with the first result of the givenfuturesthat satisfies the specifiedpredicate.static <T> Future<Option<T>>find(@NonNull java.util.concurrent.Executor executor, @NonNull java.lang.Iterable<? extends Future<? extends T>> futures, @NonNull java.util.function.Predicate<? super T> predicate)Returns aFuturethat completes with the first result of the givenfuturesthat satisfies the specifiedpredicate.static <T> Future<T>firstCompletedOf(@NonNull java.lang.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 java.util.concurrent.Executor executor, @NonNull java.lang.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>flatMap(@NonNull java.util.function.Function<? super T,? extends Future<? extends U>> mapper)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 java.lang.Iterable<? extends Future<? extends T>> futures, U zero, @NonNull java.util.function.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 java.util.concurrent.Executor executor, @NonNull java.lang.Iterable<? extends Future<? extends T>> futures, U zero, @NonNull java.util.function.BiFunction<? super U,? super T,? extends U> f)Returns aFuturecontaining the result of folding the given future values.default voidforEach(@NonNull java.util.function.Consumer<? super T> action)Performs the givenactionasynchronously when thisFuturecompletes successfully.static <T> Future<T>fromCompletableFuture(@NonNull java.util.concurrent.CompletableFuture<T> future)Creates aFuturethat wraps the givenCompletableFuture, using theDEFAULT_EXECUTORfor executing callbacks.static <T> Future<T>fromCompletableFuture(@NonNull java.util.concurrent.Executor executor, @NonNull java.util.concurrent.CompletableFuture<T> future)Creates aFuturethat wraps the givenCompletableFuture, executing callbacks using the specifiedExecutor.static <T> Future<T>fromJavaFuture(@NonNull java.util.concurrent.Executor executor, @NonNull java.util.concurrent.Future<T> future)Creates aFuturethat wraps the givenFuture, executing callbacks using the specifiedExecutor.static <T> Future<T>fromJavaFuture(@NonNull java.util.concurrent.Future<T> future)static <T> Future<T>fromTry(@NonNull Try<? extends T> result)static <T> Future<T>fromTry(@NonNull java.util.concurrent.Executor executor, @NonNull Try<? extends T> result)default Tget()Returns the value of thisFutureif it completed successfully, or throws the underlying exception if it completed with a failure.default Option<java.lang.Throwable>getCause()Returns the underlying exception.Option<Try<T>>getValue()Returns the value of thisFuture.default booleanisAsync()AFutures's value is computed asynchronously.booleanisCancelled()Checks whether thisFuturewas cancelled, i.e., its computation was interrupted before completion.booleanisCompleted()Checks 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 booleanisFailure()Checks whether thisFuturecompleted with a failure.default booleanisLazy()AFuture's value is computed eagerly.default booleanisSingleValued()AFutureis single-valued.default booleanisSuccess()Checks whether thisFuturecompleted successfully.default @NonNull Iterator<T>iterator()Returns a richio.vavr.collection.Iterator.default <U> Future<U>map(@NonNull java.util.function.Function<? super T,? extends U> mapper)Maps the underlying value to a different component type.default <U> Future<U>mapTo(U value)Maps the underlying value to another fixed value.default Future<java.lang.Void>mapToVoid()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>narrow(Future<? extends T> future)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 java.util.concurrent.Executor executor, @NonNull CheckedFunction0<? extends T> computation)Starts an asynchronous computation using the specifiedExecutor.Future<T>onComplete(@NonNull java.util.function.Consumer<? super Try<T>> action)Performs the given action once thisFutureis complete.default Future<T>onFailure(@NonNull java.util.function.Consumer<? super java.lang.Throwable> action)Performs the given action once thisFutureis complete and its result is aTry.Failure.default Future<T>onSuccess(@NonNull java.util.function.Consumer<? super T> action)Performs the given action once thisFutureis complete and its result is aTry.Success.default Future<T>orElse(@NonNull Future<? extends T> other)Returns thisFutureif it completes successfully, or the given alternativeFutureif thisFuturefails.default Future<T>orElse(@NonNull java.util.function.Supplier<? extends Future<? extends T>> supplier)Returns thisFutureif it completes successfully, or aFuturesupplied by the givenSupplierif thisFuturefails.default Future<T>peek(@NonNull java.util.function.Consumer<? super T> action)Performs the givenactionon the first element if this is an eager implementation.default Future<T>recover(@NonNull java.util.function.Function<? super java.lang.Throwable,? extends T> f)Handles a failure of thisFutureby mapping the exception to a new result.default Future<T>recoverWith(@NonNull java.util.function.Function<? super java.lang.Throwable,? extends Future<? extends T>> f)Handles a failure of thisFutureby returning the result of anotherFuture.static <T> Future<T>reduce(@NonNull java.lang.Iterable<? extends Future<? extends T>> futures, @NonNull java.util.function.BiFunction<? super T,? super T,? extends T> f)Returns aFuturecontaining the result of reducing the given future values.static <T> Future<T>reduce(@NonNull java.util.concurrent.Executor executor, @NonNull java.lang.Iterable<? extends Future<? extends T>> futures, @NonNull java.util.function.BiFunction<? super T,? super T,? extends T> f)Returns aFuturecontaining the result of reducing the given future values.static Future<java.lang.Void>run(@NonNull CheckedRunnable unit)Runs an asynchronous computation using theDEFAULT_EXECUTOR.static Future<java.lang.Void>run(@NonNull java.util.concurrent.Executor executor, @NonNull CheckedRunnable unit)Starts an asynchronous computation using the specifiedExecutor.static <T> Future<Seq<T>>sequence(@NonNull java.lang.Iterable<? extends Future<? extends T>> futures)Reduces multipleFutureinstances into a singleFutureby transforming anIterable<Future<? extends T>>into aFuture<Seq<T>>.static <T> Future<Seq<T>>sequence(@NonNull java.util.concurrent.Executor executor, @NonNull java.lang.Iterable<? extends Future<? extends T>> futures)Reduces multipleFutureinstances into a singleFutureby transforming anIterable<Future<? extends T>>into aFuture<Seq<T>>.default java.lang.StringstringPrefix()Returns the name of this Value type, which is used by toString().static <T> Future<T>successful(@NonNull java.util.concurrent.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 java.util.concurrent.CompletableFuture<T>toCompletableFuture()Converts this to aCompletableFuturedefault <U> Utransform(@NonNull java.util.function.Function<? super Future<T>,? extends U> f)Transforms the result of thisFutureusing the given function.default <U> Future<U>transformValue(@NonNull java.util.function.Function<? super Try<T>,? extends Try<? extends U>> f)Transforms the value of thisFuture, regardless of whether it completed successfully or with a failure.static <T,U>
Future<Seq<U>>traverse(@NonNull java.lang.Iterable<? extends T> values, @NonNull java.util.function.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>>.static <T,U>
Future<Seq<U>>traverse(@NonNull java.util.concurrent.Executor executor, @NonNull java.lang.Iterable<? extends T> values, @NonNull java.util.function.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>>.default <U> Future<Tuple2<T,U>>zip(@NonNull Future<? extends U> that)Combines thisFuturewith anotherFuture, returning aFutureof a tuple of both results.default <U,R>
Future<R>zipWith(@NonNull Future<? extends U> that, @NonNull java.util.function.BiFunction<? super T,? super U,? extends R> combinator)Combines thisFuturewith anotherFutureusing the 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 Detail
-
DEFAULT_EXECUTOR
static final java.util.concurrent.Executor 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:
ForkJoinPool.awaitQuiescence(long, TimeUnit)
-
-
Method Detail
-
failed
static <T> Future<T> failed(@NonNull java.lang.Throwable exception)
- 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:
java.lang.NullPointerException- ifexceptionis null
-
failed
static <T> Future<T> failed(@NonNull java.util.concurrent.Executor executor, @NonNull java.lang.Throwable exception)
Creates a failedFuturewith the givenexception, executing callbacks using the specifiedExecutor.- 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:
java.lang.NullPointerException- ifexecutororexceptionis null
-
find
static <T> Future<Option<T>> find(@NonNull java.lang.Iterable<? extends Future<? extends T>> futures, @NonNull java.util.function.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:
java.lang.NullPointerException- iffuturesorpredicateis null
-
find
static <T> Future<Option<T>> find(@NonNull java.util.concurrent.Executor executor, @NonNull java.lang.Iterable<? extends Future<? extends T>> futures, @NonNull java.util.function.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:
java.lang.NullPointerException- if any argument is null
-
firstCompletedOf
static <T> Future<T> firstCompletedOf(@NonNull java.lang.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.- 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:
java.lang.NullPointerException- iffuturesis null
-
firstCompletedOf
static <T> Future<T> firstCompletedOf(@NonNull java.util.concurrent.Executor executor, @NonNull java.lang.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:
java.lang.NullPointerException- ifexecutororfuturesis null
-
fold
static <T,U> Future<U> fold(@NonNull java.lang.Iterable<? extends Future<? extends T>> futures, U zero, @NonNull java.util.function.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:
java.lang.NullPointerException- iffuturesorfis null
-
fold
static <T,U> Future<U> fold(@NonNull java.util.concurrent.Executor executor, @NonNull java.lang.Iterable<? extends Future<? extends T>> futures, U zero, @NonNull java.util.function.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:
java.lang.NullPointerException- ifexecutor,futures, orfis null
-
fromJavaFuture
static <T> Future<T> fromJavaFuture(@NonNull java.util.concurrent.Future<T> future)
- 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:
java.lang.NullPointerException- iffutureis null
-
fromJavaFuture
static <T> Future<T> fromJavaFuture(@NonNull java.util.concurrent.Executor executor, @NonNull java.util.concurrent.Future<T> future)
Creates aFuturethat wraps the givenFuture, executing callbacks using the specifiedExecutor.- 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:
java.lang.NullPointerException- ifexecutororfutureis null
-
fromCompletableFuture
@GwtIncompatible static <T> Future<T> fromCompletableFuture(@NonNull java.util.concurrent.CompletableFuture<T> future)
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:
java.lang.NullPointerException- iffutureis null
-
fromCompletableFuture
@GwtIncompatible static <T> Future<T> fromCompletableFuture(@NonNull java.util.concurrent.Executor executor, @NonNull java.util.concurrent.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:
java.lang.NullPointerException- ifexecutororfutureis null
-
fromTry
static <T> Future<T> fromTry(@NonNull Try<? extends T> result)
- Type Parameters:
T- the type of a successful result- Parameters:
result- theTryresult to wrap- Returns:
- a completed
Futurecontaining either aSuccessor aFailure - Throws:
java.lang.NullPointerException- ifresultis null
-
fromTry
static <T> Future<T> fromTry(@NonNull java.util.concurrent.Executor executor, @NonNull Try<? extends T> result)
- 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:
java.lang.NullPointerException- ifexecutororresultis null
-
narrow
static <T> Future<T> narrow(Future<? extends T> future)
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
static <T> Future<T> of(@NonNull CheckedFunction0<? extends T> computation)
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:
java.lang.NullPointerException- ifcomputationis null
-
of
static <T> Future<T> of(@NonNull java.util.concurrent.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:
java.lang.NullPointerException- ifexecutororcomputationis null
-
reduce
static <T> Future<T> reduce(@NonNull java.lang.Iterable<? extends Future<? extends T>> futures, @NonNull java.util.function.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:
java.lang.NullPointerException- iffuturesorfis null
-
reduce
static <T> Future<T> reduce(@NonNull java.util.concurrent.Executor executor, @NonNull java.lang.Iterable<? extends Future<? extends T>> futures, @NonNull java.util.function.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:
java.lang.NullPointerException- ifexecutor,futures, orfis null
-
run
static Future<java.lang.Void> run(@NonNull CheckedRunnable unit)
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:
java.lang.NullPointerException- ifunitis null
-
run
static Future<java.lang.Void> run(@NonNull java.util.concurrent.Executor executor, @NonNull CheckedRunnable unit)
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:
java.lang.NullPointerException- ifexecutororunitis null
-
sequence
static <T> Future<Seq<T>> sequence(@NonNull java.lang.Iterable<? extends Future<? extends T>> futures)
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:
java.lang.NullPointerException- iffuturesis null
-
If all given futures succeed, the resulting future also succeeds:
-
sequence
static <T> Future<Seq<T>> sequence(@NonNull java.util.concurrent.Executor executor, @NonNull java.lang.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:
java.lang.NullPointerException- ifexecutororfuturesis null
-
successful
static <T> Future<T> successful(T result)
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
static <T> Future<T> successful(@NonNull java.util.concurrent.Executor executor, T result)
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:
java.lang.NullPointerException- ifexecutoris null
-
toCompletableFuture
@GwtIncompatible default java.util.concurrent.CompletableFuture<T> 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 java.lang.Iterable<? extends T> values, @NonNull java.util.function.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:
java.lang.NullPointerException- ifvaluesormapperis null
-
traverse
static <T,U> Future<Seq<U>> traverse(@NonNull java.util.concurrent.Executor executor, @NonNull java.lang.Iterable<? extends T> values, @NonNull java.util.function.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:
java.lang.NullPointerException- ifexecutor,values, ormapperis null
-
andThen
default Future<T> andThen(@NonNull java.util.function.Consumer<? super Try<T>> action)
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:
java.lang.NullPointerException- ifactionis null
-
await
Future<T> 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
Future<T> await(long timeout, java.util.concurrent.TimeUnit unit)
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:
java.lang.IllegalArgumentException- iftimeoutis negativejava.lang.NullPointerException- 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:
java.lang.SecurityException- if the current thread is not permitted to modify the Future's thread- See Also:
isCancelled()
-
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:
java.lang.SecurityException- if the current thread is not permitted to modify the Future's thread- See Also:
isCancelled(),Future.cancel(boolean)
-
collect
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. 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:
java.lang.NullPointerException- ifpartialFunctionis null
-
executor
default java.util.concurrent.Executor executor()
Returns theExecutorthat executes asynchronous handlers for thisFuture.- Returns:
- the underlying
Executor
-
executorService
@Deprecated java.util.concurrent.ExecutorService executorService() throws java.lang.UnsupportedOperationExceptionDeprecated.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:
java.lang.UnsupportedOperationException- if the underlyingExecutorisn't anExecutorService.
-
failed
default Future<java.lang.Throwable> 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
default Future<T> fallbackTo(@NonNull Future<? extends T> that)
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:
java.lang.NullPointerException- ifthatis null
-
filter
default Future<T> filter(@NonNull java.util.function.Predicate<? super T> predicate)
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:
java.lang.NullPointerException- ifpredicateis null
-
filterTry
default Future<T> filterTry(@NonNull CheckedPredicate<? super T> predicate)
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:
java.lang.NullPointerException- ifpredicateis null
-
getCause
default Option<java.lang.Throwable> 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:
java.lang.UnsupportedOperationException- if theFuturecompleted successfully with a value
-
getValue
Option<Try<T>> getValue()
Returns the value of thisFuture.- Returns:
Noneif theFutureis not yet completed or was cancelled; otherwise,Some(Try)containing the result or failure
-
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
Future<T> onComplete(@NonNull java.util.function.Consumer<? super Try<T>> action)
Performs the given action once thisFutureis complete.- Parameters:
action- an action to execute when the future completes- Returns:
- this
Future - Throws:
java.lang.NullPointerException- ifactionis null
-
onFailure
default Future<T> onFailure(@NonNull java.util.function.Consumer<? super java.lang.Throwable> action)
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:
java.lang.NullPointerException- ifactionis null
-
onSuccess
default Future<T> onSuccess(@NonNull java.util.function.Consumer<? super T> action)
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:
java.lang.NullPointerException- ifactionis null
-
recover
default Future<T> recover(@NonNull java.util.function.Function<? super java.lang.Throwable,? extends T> f)
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:
java.lang.NullPointerException- iffis null
-
recoverWith
default Future<T> recoverWith(@NonNull java.util.function.Function<? super java.lang.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:
java.lang.NullPointerException- iffis null
-
transform
default <U> U transform(@NonNull java.util.function.Function<? super Future<T>,? extends U> f)
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:
java.lang.NullPointerException- iffis null
-
transformValue
default <U> Future<U> transformValue(@NonNull java.util.function.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:
java.lang.NullPointerException- iffis null
-
zip
default <U> Future<Tuple2<T,U>> zip(@NonNull Future<? extends U> that)
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:
java.lang.NullPointerException- ifthatis null
-
zipWith
default <U,R> Future<R> zipWith(@NonNull Future<? extends U> that, @NonNull java.util.function.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:
java.lang.NullPointerException- ifthatorcombinatoris null
-
flatMap
default <U> Future<U> flatMap(@NonNull java.util.function.Function<? super T,? extends Future<? extends U>> mapper)
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:
java.lang.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:
java.lang.NullPointerException- ifmapperisnull
-
forEach
default void forEach(@NonNull java.util.function.Consumer<? super T> action)
Performs the givenactionasynchronously when thisFuturecompletes successfully.The
actionis not executed if theFuturecompletes with a failure.
-
get
default T 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
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()
AFutureis single-valued.- Specified by:
isSingleValuedin interfaceValue<T>- Returns:
true
-
iterator
default @NonNull Iterator<T> iterator()
Description copied from interface:ValueReturns a richio.vavr.collection.Iterator.
-
map
default <U> Future<U> map(@NonNull java.util.function.Function<? super T,? extends U> mapper)
Description copied from interface:ValueMaps the underlying value to a different component type.
-
mapTo
default <U> Future<U> mapTo(U value)
Description copied from interface:ValueMaps the underlying value to another fixed value.
-
mapToVoid
default Future<java.lang.Void> mapToVoid()
Description copied from interface:ValueMaps the underlying value to Void
-
mapTry
default <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.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:
java.lang.NullPointerException- ifmapperisnull
-
orElse
default Future<T> orElse(@NonNull Future<? extends T> other)
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:
java.lang.NullPointerException- ifotheris null
-
orElse
default Future<T> orElse(@NonNull java.util.function.Supplier<? extends Future<? extends T>> supplier)
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:
java.lang.NullPointerException- ifsupplieris null
-
peek
default Future<T> peek(@NonNull java.util.function.Consumer<? super T> action)
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
default java.lang.String 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.
-
-