Package com.apple.foundationdb.async
Class MoreAsyncUtil
java.lang.Object
com.apple.foundationdb.async.MoreAsyncUtil
More helpers in the spirit of
AsyncUtil
.-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic class
ABoolean
function that is always true.static class
Exception that will be thrown when thesupplier
ingetWithDeadline(long, Supplier, ScheduledExecutorService)
fails to complete within the specified deadline time.static class
A holder for a (mutable) value. -
Method Summary
Modifier and TypeMethodDescriptionstatic <T> CompletableFuture<T>
static void
closeIterator
(Iterator<?> iterator) Close the given iterator, or at least cancel it.static <T,
U, R> CompletableFuture<R> combineAndFailFast
(CompletableFuture<T> future1, CompletableFuture<U> future2, BiFunction<T, U, R> combiner) Combine the results of two futures, but fail fast if either future fails.static <V> CompletableFuture<V>
composeWhenComplete
(CompletableFuture<V> future, BiFunction<V, Throwable, CompletableFuture<Void>> handler, Function<Throwable, RuntimeException> exceptionMapper) This is supposed to replicate the semantics ofCompletionStage.whenComplete(BiConsumer)
but to handle the case where the completion handler might itself contain async work.static <V,
T> CompletableFuture<T> composeWhenCompleteAndHandle
(CompletableFuture<V> future, BiFunction<V, Throwable, ? extends CompletableFuture<T>> handler, Function<Throwable, RuntimeException> exceptionMapper) Compose a handler bi-function to the result of a future.static <T> AsyncIterable<T>
concatIterables
(AsyncIterable<T>... iterables) Create a new iterable that has the contents of all the parameters in order.static <T> AsyncIterable<T>
concatIterables
(Executor executor, AsyncIterable<T>... iterables) static <T> AsyncIterable<T>
dedupIterable
(AsyncIterable<T> iterable) Remove adjacent duplicates form iterable.static <T> AsyncIterable<T>
dedupIterable
(Executor executor, AsyncIterable<T> iterable) static CompletableFuture<Void>
delayedFuture
(long delay, TimeUnit unit) Creates a future that will be ready after the given delay.static CompletableFuture<Void>
delayedFuture
(long delay, TimeUnit unit, ScheduledExecutorService scheduledExecutor) Creates a future that will be ready after the given delay.static <T> AsyncIterable<T>
filterIterable
(AsyncIterable<T> iterable, Function<T, Boolean> filter) Filter items from an async iterable.static <T> AsyncIterable<T>
filterIterable
(Executor executor, AsyncIterable<T> iterable, Function<T, Boolean> filter) static <T> AsyncIterable<T>
filterIterablePipelined
(AsyncIterable<T> iterable, Function<T, CompletableFuture<Boolean>> filter, int pipelineSize) Filter an iterable, pipelining the asynchronous filter functions.static <T> AsyncIterable<T>
filterIterablePipelined
(Executor executor, AsyncIterable<T> iterable, Function<T, CompletableFuture<Boolean>> filter, int pipelineSize) static ScheduledExecutorService
Get the default scheduled executor service.static <T> CompletableFuture<T>
getWithDeadline
(long deadlineTimeMillis, Supplier<CompletableFuture<T>> supplier, ScheduledExecutorService scheduledExecutor) Get a completable future that will either complete within the specified deadline time or complete exceptionally withMoreAsyncUtil.DeadlineExceededException
.static <V> CompletableFuture<V>
handleOnException
(Supplier<CompletableFuture<V>> futureSupplier, Function<Throwable, CompletableFuture<V>> handlerOnException) Handle whenfutureSupplier
encounters an exception when supplying a future, or the future is completed exceptionally.static boolean
isCompletedNormally
(CompletableFuture<?> future) Returns whether the givenCompletableFuture
has completed normally, i.e., not exceptionally.static <T> AsyncIterable<T>
limitIterable
(AsyncIterable<T> iterable, int limit) static <T1,
T2> AsyncIterable<T2> mapConcatIterable
(AsyncIterable<T1> iterable, Function<T1, AsyncIterable<T2>> func, int pipelineSize) Maps each value in an iterable to a new iterable and returns the concatenated results.static <T1,
T2> AsyncIterable<T2> mapConcatIterable
(Executor executor, AsyncIterable<T1> iterable, Function<T1, AsyncIterable<T2>> func, int pipelineSize) static <T1,
T2> AsyncIterable<T2> mapIterablePipelined
(AsyncIterable<T1> iterable, Function<T1, CompletableFuture<T2>> func, int pipelineSize) Maps an AsyncIterable using an asynchronous mapping function.static <U,
T> CompletableFuture<U> reduce
(AsyncIterator<T> iterator, U identity, BiFunction<U, ? super T, U> accumulator) Reduce contents of iterator to single value.static <U,
T> CompletableFuture<U> reduce
(Executor executor, AsyncIterator<T> iterator, U identity, BiFunction<U, ? super T, U> accumulator) static CompletableFuture<Void>
swallowException
(CompletableFuture<Void> future, Predicate<Throwable> shouldSwallow) Swallows exceptions matching a given predicate from a future.
-
Method Details
-
alreadyCancelled
-
limitIterable
@Nonnull public static <T> AsyncIterable<T> limitIterable(@Nonnull AsyncIterable<T> iterable, int limit) -
filterIterable
@Nonnull public static <T> AsyncIterable<T> filterIterable(@Nonnull AsyncIterable<T> iterable, @Nonnull Function<T, Boolean> filter) Filter items from an async iterable.- Type Parameters:
T
- the source type- Parameters:
iterable
- the sourcefilter
- only items in iterable for which this function returns true will appear in the return value- Returns:
- a new
AsyncIterable
that only contains those items in iterable for which filter returnstrue
-
filterIterable
@Nonnull public static <T> AsyncIterable<T> filterIterable(@Nonnull Executor executor, @Nonnull AsyncIterable<T> iterable, @Nonnull Function<T, Boolean> filter) -
dedupIterable
Remove adjacent duplicates form iterable. Note: if iterable is sorted, this will actually remove duplicates.- Type Parameters:
T
- the source type- Parameters:
iterable
- the source- Returns:
- a new
AsyncIterable
that only contains those items in iterable for which the previous item was different
-
dedupIterable
@Nonnull public static <T> AsyncIterable<T> dedupIterable(@Nonnull Executor executor, @Nonnull AsyncIterable<T> iterable) -
concatIterables
Create a new iterable that has the contents of all the parameters in order.- Type Parameters:
T
- the source type- Parameters:
iterables
- a list of iterables to concatenate together- Returns:
- a new
AsyncIterable
that starts with all the elements of the first iterable provided, then all the elements of the second iterable and so on
-
concatIterables
@Nonnull public static <T> AsyncIterable<T> concatIterables(@Nonnull Executor executor, @Nonnull AsyncIterable<T>... iterables) -
mapConcatIterable
@Nonnull public static <T1,T2> AsyncIterable<T2> mapConcatIterable(@Nonnull AsyncIterable<T1> iterable, @Nonnull Function<T1, AsyncIterable<T2>> func, int pipelineSize) Maps each value in an iterable to a new iterable and returns the concatenated results. This will start a pipeline of asynchronous requests for up to a requested number of elements of the iterable, in parallel with requests to the mapping results. This does not pipeline the overlapping concatenations, i.e. it won't grab the first item of the second result of func, until it has exhausted the first result of func.- Type Parameters:
T1
- the type of the sourceT2
- the type of the destination iterables- Parameters:
iterable
- the sourcefunc
- mapping function from each element of iterable to a new iterablepipelineSize
- the number of elements to pipeline- Returns:
- the results of all the
AsyncIterable
s returned by func for each value of iterable, concatenated
-
mapConcatIterable
@Nonnull public static <T1,T2> AsyncIterable<T2> mapConcatIterable(@Nonnull Executor executor, @Nonnull AsyncIterable<T1> iterable, @Nonnull Function<T1, AsyncIterable<T2>> func, int pipelineSize) -
filterIterablePipelined
@Nonnull public static <T> AsyncIterable<T> filterIterablePipelined(@Nonnull AsyncIterable<T> iterable, @Nonnull Function<T, CompletableFuture<Boolean>> filter, int pipelineSize) Filter an iterable, pipelining the asynchronous filter functions. Unlike filterIterable, the filter here is asynchronous. As items comes back from iterable, a pipeline of filter futures is kept without advancing the iterable.- Type Parameters:
T
- the source type- Parameters:
iterable
- the sourcefilter
- only the values of iterable for which the future returned by this filter returns true will be in the resulting iterablepipelineSize
- the number of filter results to pipeline- Returns:
- a new
AsyncIterable
containing the elements of iterable for which filter returns a true future
-
filterIterablePipelined
@Nonnull public static <T> AsyncIterable<T> filterIterablePipelined(@Nonnull Executor executor, @Nonnull AsyncIterable<T> iterable, @Nonnull Function<T, CompletableFuture<Boolean>> filter, int pipelineSize) -
mapIterablePipelined
@Nonnull public static <T1,T2> AsyncIterable<T2> mapIterablePipelined(@Nonnull AsyncIterable<T1> iterable, @Nonnull Function<T1, CompletableFuture<T2>> func, int pipelineSize) Maps an AsyncIterable using an asynchronous mapping function.- Type Parameters:
T1
- the source typeT2
- the destination type- Parameters:
iterable
- the sourcefunc
- Maps items of iterable to a new value asynchronouslypipelineSize
- the number of map results to pipeline. As items comes back from iterable, this will have up to this many func futures in waiting before waiting on them without advancing the iterable.- Returns:
- a new
AsyncIterable
with the results of applying func to each of the elements of iterable
-
reduce
@Nullable public static <U,T> CompletableFuture<U> reduce(@Nonnull AsyncIterator<T> iterator, U identity, BiFunction<U, ? super T, U> accumulator) Reduce contents of iterator to single value.- Type Parameters:
U
- the result type of the reductionT
- the element type of the iterator- Parameters:
iterator
- source of valuesidentity
- initial value for reductionaccumulator
- function that takes previous reduced value and computes new value combining iterator element- Returns:
- the reduced result
-
reduce
@Nullable public static <U,T> CompletableFuture<U> reduce(@Nonnull Executor executor, @Nonnull AsyncIterator<T> iterator, U identity, BiFunction<U, ? super T, U> accumulator) -
isCompletedNormally
Returns whether the givenCompletableFuture
has completed normally, i.e., not exceptionally. If the future is yet to complete or if the future completed with an error, then this will returnfalse
.- Parameters:
future
- the future to check for normal completion- Returns:
- whether the future has completed without exception
-
getDefaultScheduledExecutor
Get the default scheduled executor service. This is used to schedule delayed tasks in an efficient way bydelayedFuture(long, TimeUnit)
. Adopters can provide their ownScheduledExecutorService
by using the overloaded method.By default, the returned executor service is a
ScheduledThreadPoolExecutor
with a single thread used for executing delayed tasks. In practice, with a future chain, this should be quick asynchronous callbacks, and blocking in such a callback can block the task thread.- Returns:
- an executor service that allows for tasks to be efficiently scheduled for later
- See Also:
-
delayedFuture
@API(UNSTABLE) @Nonnull public static CompletableFuture<Void> delayedFuture(long delay, @Nonnull TimeUnit unit) Creates a future that will be ready after the given delay. This uses thegetDefaultScheduledExecutor()
to schedule tasks but is otherwise identical todelayedFuture(long, TimeUnit, ScheduledExecutorService)
.- Parameters:
delay
- the time from now to delay executionunit
- the time unit of the delay parameter- Returns:
- a future that will be ready after the given delay
- See Also:
-
delayedFuture
@API(UNSTABLE) @Nonnull public static CompletableFuture<Void> delayedFuture(long delay, @Nonnull TimeUnit unit, @Nonnull ScheduledExecutorService scheduledExecutor) Creates a future that will be ready after the given delay. The delayed future will be executed using the suppliedScheduledExecutorService
to complete the returned future. Exact performance can depend on the scheduled executor implementation, but it should generally be safe to create many delayed futures at once. The guarantee given by this function is that the future will not be ready sooner than the delay specified. It may, however, fire after the given delay (especially if there are multiple delayed futures that are trying to fire at once).- Parameters:
delay
- the time from now to delay executionunit
- the time unit of the delay parameterscheduledExecutor
- executor service used to complete the returned future and run any same-thread callbacks- Returns:
- a
CompletableFuture
that will fire after the given delay
-
getWithDeadline
@API(EXPERIMENTAL) public static <T> CompletableFuture<T> getWithDeadline(long deadlineTimeMillis, @Nonnull Supplier<CompletableFuture<T>> supplier, @Nonnull ScheduledExecutorService scheduledExecutor) Get a completable future that will either complete within the specified deadline time or complete exceptionally withMoreAsyncUtil.DeadlineExceededException
. IfdeadlineTimeMillis
is set toLong.MAX_VALUE
, then no deadline is imposed on the future.- Type Parameters:
T
- the return type for the get operation- Parameters:
deadlineTimeMillis
- the maximum time to wait for the asynchronous operation to complete, specified in millisecondssupplier
- theSupplier
of the asynchronous resultscheduledExecutor
- executor used to handle managing the deadline- Returns:
- a future that will either complete with the result of the asynchronous get operation or complete exceptionally if the deadline is exceeded
-
closeIterator
Close the given iterator, or at least cancel it.- Parameters:
iterator
- iterator to close
-
composeWhenComplete
public static <V> CompletableFuture<V> composeWhenComplete(@Nonnull CompletableFuture<V> future, @Nonnull BiFunction<V, Throwable, CompletableFuture<Void>> handler, @Nullable Function<Throwable, RuntimeException> exceptionMapper) This is supposed to replicate the semantics ofCompletionStage.whenComplete(BiConsumer)
but to handle the case where the completion handler might itself contain async work.- Type Parameters:
V
- return type of original future- Parameters:
future
- future to compose the handler ontohandler
- handler bi-function to compose onto the passed futureexceptionMapper
- function for mapping the underlying exception to aRuntimeException
- Returns:
- future with same completion properties as the future returned by the handler
- See Also:
-
composeWhenCompleteAndHandle
public static <V,T> CompletableFuture<T> composeWhenCompleteAndHandle(@Nonnull CompletableFuture<V> future, @Nonnull BiFunction<V, Throwable, ? extends CompletableFuture<T>> handler, @Nullable Function<Throwable, RuntimeException> exceptionMapper) Compose a handler bi-function to the result of a future. Unlike theAsyncUtil.composeHandle(CompletableFuture, BiFunction)
, which completes exceptionally only when thehandler
completes exceptionally, it completes exceptionally even if the supplied action itself (future
) encounters an exception.- Type Parameters:
V
- type of original futureT
- type of final future- Parameters:
future
- future to compose the handler ontohandler
- handler bi-function to compose onto the passed futureexceptionMapper
- function for mapping the underlying exception to aRuntimeException
- Returns:
- future with same completion properties as the future returned by the handler
- See Also:
-
handleOnException
public static <V> CompletableFuture<V> handleOnException(Supplier<CompletableFuture<V>> futureSupplier, Function<Throwable, CompletableFuture<V>> handlerOnException) Handle whenfutureSupplier
encounters an exception when supplying a future, or the future is completed exceptionally. Unlike the "handle" in CompletableFuture,handlerOnException
is not executed if the future is successful.- Type Parameters:
V
- the result type of the future- Parameters:
futureSupplier
- the supplier of future which needs to be handledhandlerOnException
- the handler when the future encounters an exception- Returns:
- future that completes exceptionally if the handler has exception
-
combineAndFailFast
public static <T,U, CompletableFuture<R> combineAndFailFastR> (CompletableFuture<T> future1, CompletableFuture<U> future2, BiFunction<T, U, R> combiner) Combine the results of two futures, but fail fast if either future fails.This has the same behavior as
CompletableFuture.thenCombine(java.util.concurrent.CompletionStage<? extends U>, java.util.function.BiFunction<? super T, ? super U, ? extends V>)
, except, if either future fails, it won't wait for the other one to complete before completing the result with the failure.- Type Parameters:
T
- the result type forfuture1
U
- the result type forfuture2
R
- the result type for the returned future- Parameters:
future1
- one futurefuture2
- another futurecombiner
- a function to combine the results of bothfuture1
andfuture2
into a single result.- Returns:
- a future that fails with one of the exceptions from
future1
orfuture2
if either of those failed, or the result of applyingcombiner
to their results if both succeeded.
-
swallowException
public static CompletableFuture<Void> swallowException(@Nonnull CompletableFuture<Void> future, @Nonnull Predicate<Throwable> shouldSwallow) Swallows exceptions matching a given predicate from a future.- Parameters:
future
- a future which you expect to potentially throw an exceptionshouldSwallow
- a predicate on whether to swallow the error from the future. Note that if the future failed with aCompletionException
,swallowException
will also be called with its cause so that you don't need special handling to cover this.- Returns:
- a future that will complete successfully if
future
completed successfully, or theshouldSwallow
predicate returnedtrue
for the error thatfuture
threw
-