Class ParallelScope

java.lang.Object
groovy.concurrent.ParallelScope

public final class ParallelScope extends Object
Convenience API for running work within a pool-isolated AsyncScope.

ParallelScope combines Pool and AsyncScope in a single call: the pool is created (or provided), used as the executor for the scope, and shut down when the scope exits.

This is the Groovy successor to GPars' GParsPool.withPool and PGroup scoping pattern, modernised for structured concurrency and virtual threads.


 // Groovy:
 ParallelScope.withPool(4) { scope ->
     def a = scope.async { cpuWork1() }
     def b = scope.async { cpuWork2() }
     [await(a), await(b)]
 }

 // With a pre-configured pool:
 def pool = Pool.cpu()
 ParallelScope.withPool(pool) { scope ->
     scope.async { work() }
     null
 }
 pool.close()
 
Since:
6.0.0
See Also:
  • Method Details

    • withPool

      public static <T> T withPool(int threads, Function<AsyncScope,T> body)
      Creates a fixed-size pool, executes the body within a scoped context, and shuts down the pool on exit.
      Type Parameters:
      T - the result type
      Parameters:
      threads - the number of threads in the pool
      body - the function receiving the scope
      Returns:
      the body's return value
    • withPool

      public static <T> T withPool(Pool pool, Function<AsyncScope,T> body)
      Executes the body within a scope backed by the given pool.

      The pool is not shut down on exit — the caller owns the pool's lifecycle. Both AsyncScope.current() and Pool.current() are bound for the duration.

      Type Parameters:
      T - the result type
      Parameters:
      pool - the pool to use as executor
      body - the function receiving the scope
      Returns:
      the body's return value