Class AsyncSupport
async/await/defer language features.
This class is the entry point invoked by compiler-generated code and also
exposes the combinator and configuration surface used by
Awaitable. Combinator algorithms live in
AwaitCombinators; executor/scheduler configuration lives in
AsyncExecutors.
Thread pool configuration:
- On JDK 21+ the default executor is a virtual-thread-per-task executor.
Virtual threads make blocking within
await()essentially free. - On JDK 17-20 the fallback is a cached daemon thread pool
whose maximum size is controlled by the system property
groovy.async.parallelism(default:256). - The executor can be overridden via
setExecutor(java.util.concurrent.Executor); passnullto restore the platform default.
Exception handling follows a transparency principle: the original exception is rethrown without being wrapped.
- Since:
- 6.0.0
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionstatic <T> List<T>Waits for all given sources to complete, returning their results in order.Non-blocking variant ofall(java.lang.Object...)— returns an Awaitable.static List<AwaitResult<Object>>allSettled(Object... sources) Waits for all sources to settle (succeed or fail), returning a list ofAwaitResultwithout throwing.static Awaitable<List<AwaitResult<Object>>>allSettledAsync(Object... sources) Non-blocking variant ofallSettled(java.lang.Object...)— returns an Awaitable.static <T> TReturns the result of the first source to complete (success or failure).static <T> Awaitable<T>Non-blocking variant ofany(java.lang.Object...)— returns an Awaitable.static <T> Awaitable<T>Executes the given supplier asynchronously using the default executor.static <T> Iterable<T>asyncGenerator(Consumer<Object> body) Starts a generator immediately, returning anIterablebacked by aGeneratorBridge.static <T> TAwaits the result of anAwaitable.static <T> TAwaits an arbitrary object by adapting it viaAwaitable.from(Object).static <T> Tawait(CompletableFuture<T> future) Awaits aCompletableFutureusing non-interruptiblejoin().static <T> Tawait(CompletionStage<T> stage) Awaits aCompletionStageby converting to CompletableFuture.static <T> TAwaits aFuture.static voidcloseIterable(Object source) Closes a source if it implementsCloseableorAutoCloseable.static <T> Awaitable<T>completeOnTimeout(Object source, T fallback, long timeout, TimeUnit unit) Wraps a source with a timeout that uses a fallback value instead of throwing.static <T> Awaitable<T>completeOnTimeoutMillis(Object source, T fallback, long millis) Convenience: timeout in milliseconds.Creates a new defer scope (LIFO stack of cleanup actions).static voidRegisters a deferred action in the given scope.delay(long millis) Returns an Awaitable that completes after the specified delay.Delay with explicit time unit.static <T> Awaitable<T>executeAsync(Supplier<T> supplier, Executor executor) Executes the given supplier asynchronously on the specified executor, returning anAwaitable.static voidexecuteDeferScope(Deque<Callable<?>> scope) Executes all deferred actions in LIFO order.static <T> TReturns the result of the first source to complete successfully.static <T> Awaitable<T>firstAsync(Object... sources) Non-blocking variant offirst(java.lang.Object...)— returns an Awaitable.static ExecutorReturns the current executor used for async tasks.static ScheduledExecutorServiceReturns the shared scheduler for delays, timeouts, and scope deadlines.static <T> Awaitable<T>Lightweight task spawn.static booleanReturnstrueif running on JDK 21+ with virtual thread support.static <T> Awaitable<T>Wraps a source with a timeout.static <T> Awaitable<T>orTimeoutMillis(Object source, long millis) Convenience: timeout in milliseconds.static voidResets the executor to the platform default.static RuntimeExceptionRethrowsfailureas itself, including a checked exception, so that async constructs surface the same exception synchronous code would.static voidsetExecutor(Executor executor) Sets the executor used for async tasks.static <T> Iterable<T>toIterable(Object source) Converts an arbitrary source to anIterablefor use infor awaitloops.static ThrowableStrips JDK wrapper layers (CompletionException,ExecutionException,InvocationTargetException,UndeclaredThrowableException) to expose the original cause.static ThrowableRemoves theUndeclaredThrowableExceptionthat converting a closure to a functional interface such asFunctionorConsumerputs around a checked exception.static CompletionExceptionReturnstwhen it is already aCompletionException.static voidyieldReturn(Object bridge, Object value) Called by compiler-generated code foryield return exprinside an async generator closure.
-
Method Details
-
getScheduler
Returns the shared scheduler for delays, timeouts, and scope deadlines. -
isVirtualThreadsAvailable
public static boolean isVirtualThreadsAvailable()Returnstrueif running on JDK 21+ with virtual thread support. -
getExecutor
Returns the current executor used for async tasks. -
setExecutor
Sets the executor used for async tasks.Pass
nullto restore the platform default (virtual threads on JDK 21+, cached daemon pool otherwise). The change takes effect for subsequentasynclaunches; in-flight tasks keep the executor that started them.- Parameters:
executor- the executor to use, ornullto reset
-
resetExecutor
public static void resetExecutor()Resets the executor to the platform default. Equivalent tosetExecutor(null). -
await
Awaits the result of anAwaitable. Blocks the calling thread until the computation completes. The original exception is rethrown transparently. -
await
Awaits aCompletableFutureusing non-interruptiblejoin(). -
await
Awaits aCompletionStageby converting to CompletableFuture. -
await
Awaits aFuture. Delegates to the CF overload if applicable. -
await
Awaits an arbitrary object by adapting it viaAwaitable.from(Object).This is the fallback overload called by compiler-generated
awaitexpressions. The compiler inserts a cast toObjectso that overload resolution does not have to choose amongAwaitable,CompletionStage, andFuturewhen a value implements more than one of them (e.g.CompletableFuture). -
executeAsync
Executes the given supplier asynchronously on the specified executor, returning anAwaitable. -
async
Executes the given supplier asynchronously using the default executor. -
go
Lightweight task spawn. Alias ofasync(Supplier)for Go-style ergonomics; semantics are identical. -
createDeferScope
Creates a new defer scope (LIFO stack of cleanup actions). Called by compiler-generated code at the start of closures containingdeferstatements. -
defer
Registers a deferred action in the given scope. Actions execute in LIFO order whenexecuteDeferScope(java.util.Deque<java.util.concurrent.Callable<?>>)is called (in the finally block). -
executeDeferScope
Executes all deferred actions in LIFO order. If multiple actions throw, subsequent exceptions are added as suppressed. If a deferred action returns a Future/Awaitable, the result is awaited before continuing. -
yieldReturn
Called by compiler-generated code foryield return exprinside an async generator closure. Delegates to the bridge's yield method.- Parameters:
bridge- the GeneratorBridge instance (injected as synthetic parameter)value- the value to yield
-
asyncGenerator
Starts a generator immediately, returning anIterablebacked by aGeneratorBridge. The consumer receives the bridge as its argument and should callyieldReturn(java.lang.Object, java.lang.Object)to produce values.This is the runtime entry point for
async { ... yield return ... }expressions. The compiler generates a closure that SAM-coerces toConsumer<Object>.- Type Parameters:
T- the element type- Parameters:
body- the generator body; receives aGeneratorBridge- Returns:
- an Iterable that yields values from the generator
-
toIterable
Converts an arbitrary source to anIterablefor use infor awaitloops. Handles arrays, collections, iterables, iterators, and adapter-supported types. The returned iterable may block onnext()for async sources.- Type Parameters:
T- the element type- Parameters:
source- the source to convert- Returns:
- an iterable
-
closeIterable
Closes a source if it implementsCloseableorAutoCloseable. Called by compiler-generated finally block infor awaitloops. Cleanup exceptions are swallowed so they cannot mask the original loop error; prefer robustclose()implementations. -
all
Waits for all given sources to complete, returning their results in order. Multi-argawait(a, b, c)desugars to the non-blockingallAsync(Object...)form, then awaits it. -
any
Returns the result of the first source to complete (success or failure). -
first
Returns the result of the first source to complete successfully. Only fails when all sources fail (aggregateCompletionException;awaittransparency rethrows the cause). -
allSettled
Waits for all sources to settle (succeed or fail), returning a list ofAwaitResultwithout throwing. -
allAsync
Non-blocking variant ofall(java.lang.Object...)— returns an Awaitable. -
anyAsync
Non-blocking variant ofany(java.lang.Object...)— returns an Awaitable. -
firstAsync
Non-blocking variant offirst(java.lang.Object...)— returns an Awaitable. -
allSettledAsync
Non-blocking variant ofallSettled(java.lang.Object...)— returns an Awaitable. -
delay
Returns an Awaitable that completes after the specified delay. -
delay
Delay with explicit time unit. -
orTimeout
Wraps a source with a timeout. If the source does not complete within the specified time, the returned Awaitable fails withTimeoutExceptionand the underlying computation is cancelled. -
orTimeoutMillis
Convenience: timeout in milliseconds. -
completeOnTimeout
public static <T> Awaitable<T> completeOnTimeout(Object source, T fallback, long timeout, TimeUnit unit) Wraps a source with a timeout that uses a fallback value instead of throwing. On timeout the underlying computation is cancelled. -
completeOnTimeoutMillis
Convenience: timeout in milliseconds. -
wrapForFuture
Returnstwhen it is already aCompletionException. Otherwise returns a newCompletionExceptioncaused byt.- Parameters:
t- the failure to complete a future with; may benull- Returns:
tif it is aCompletionException, otherwise a wrapper around it
-
unwrap
Strips JDK wrapper layers (CompletionException,ExecutionException,InvocationTargetException,UndeclaredThrowableException) to expose the original cause. Exceptions suppressed by a removed layer move to the cause. -
unwrapUndeclared
Removes theUndeclaredThrowableExceptionthat converting a closure to a functional interface such asFunctionorConsumerputs around a checked exception. Only that layer is removed: any other wrapper, including one the code threw itself, is returned unchanged. Exceptions suppressed by the removed layer move to the checked exception.Internal runtime support, public only for use by
groovy.concurrent.- Parameters:
t- the exception thrown through the converted closure- Returns:
- the checked exception it carries, or
titself
-
rethrow
Rethrowsfailureas itself, including a checked exception, so that async constructs surface the same exception synchronous code would. Kept in this package so the pure-Java concurrent jar stays self-contained.Internal runtime support, public only for use by
groovy.concurrent.- Parameters:
failure- the exception to rethrow- Returns:
- never returns normally; declared so callers can write
throw rethrow(t)
-