1. Introduction

Groovy adds parallel collection methods directly onto Collection, enabling data parallelism with familiar Groovy idioms. A fork-join pool, including the common pool, runs a Java parallel stream on that pool. A pool that is not a fork-join pool submits one task per element to itself. See Pool and ParallelScope for the parallelism cap and for Pool.virtual() / Pool.io().

All methods use java.util.function types (Consumer, Function, Predicate, etc.) and Groovy closures are automatically converted via SAM coercion.

2. Getting Started

Parallel methods are available on any Collection without imports:

def result = (1..1000).toList().collectParallel { it * 2 }
assert result.sort() == (2..2000).step(2).toList()

By default, operations run on ForkJoinPool.commonPool(). For pool isolation, use ParallelScope.withPool:

import groovy.concurrent.ParallelScope
import groovy.concurrent.Pool

ParallelScope.withPool(Pool.cpu()) { scope ->
    def bigList = (1..100_000).toList()
    def sum = bigList.injectParallel(0) { a, b -> a + b }
    println "Sum: $sum"
}

3. Pool and ParallelScope

3.1. Pool

Pool is a managed thread pool extending Executor and AutoCloseable:

import groovy.concurrent.Pool

def pool = Pool.cpu()       // Sized to available processors (ForkJoinPool)
def pool2 = Pool.fixed(8)   // Fixed-size ForkJoinPool
def pool3 = Pool.io()       // Virtual threads on JDK 21+, sized pool otherwise
def pool4 = Pool.virtual()  // Virtual-thread-per-task (JDK 21+)

Pool.cpu() and Pool.fixed(n) create ForkJoinPool-backed pools for CPU-bound parallel work. Parallelism is a hard cap of n (or the processor count): parallel collection methods do not add workers for a blocked or CPU-bound callback, and they do not enlarge ForkJoinPool.commonPool().

A callback that blocks (a barrier, a lock, or I/O) holds the worker running it. On a fork-join pool that can stall the operation when every worker blocks while a sibling task is still queued. Size the pool to at least one more thread than the number of concurrent blockers (ParallelScope.withPool(blockers + 1)).

Pool.virtual(), and Pool.io() on JDK 21 and later, are not fork-join pools. Parallel collection methods then submit one task per element to that pool, so a blocking callback stays off the common pool and does not raise the cap of Pool.fixed. On older JDKs Pool.io() is a fixed fork-join pool of ConcurrentConfig.defaultParallelism, and the spare-worker rule applies. CPU-bound work should stay on Pool.fixed or Pool.cpu().

On the executor path, a short-circuit (findParallel, findAnyParallel, anyParallel, or everyParallel) or a sibling failure interrupts callbacks that are still running, and interrupting a thread blocked on an InterruptibleChannel (for example a FileChannel) closes the channel. A fork-join pool does not interrupt a running callback.

A nested parallel collection call stays on the current pool. Each worker a Pool creates carries that pool, and Pool.current() uses it when the thread has no explicit binding, so a callback does not rebind the pool per element. The nested call therefore does not fall through to ForkJoinPool.commonPool(). On a bounded executor that does not grow, the nested call runs on the worker already executing the outer element, so that worker does not wait for a task queued behind it. Pool.virtual() still runs each element as its own task.

3.2. ParallelScope

ParallelScope.withPool binds a pool for the duration of a block. Parallel collection methods inside the block automatically use it:

import groovy.concurrent.ParallelScope
import groovy.concurrent.Pool

ParallelScope.withPool(4) { scope ->
    // All *Parallel methods use a 4-thread ForkJoinPool
    def results = bigList.collectParallel { transform(it) }
    def filtered = results.findAllParallel { it > threshold }
    filtered.eachParallel { process(it) }
}
// Pool is shut down automatically

3.3. ConcurrentConfig

Global defaults are managed by ConcurrentConfig:

import groovy.concurrent.ConcurrentConfig

// Default parallelism: processors + 1 (GPars convention)
println ConcurrentConfig.defaultParallelism

// Override via system property: -Dgroovy.concurrent.poolsize=16
// Or programmatically:
ConcurrentConfig.defaultParallelism = 16

4. Parallel Collection Methods

4.1. Transformation

Method Description

collectParallel { }

Transforms each element (parallel map)

collectManyParallel { }

Transforms and flattens (parallel flatMap)

collectManyParallel()

Flattens a collection of collections

def names = people.collectParallel { it.name }
def allTags = articles.collectManyParallel { it.tags }

4.2. Filtering

Method Description

findAllParallel { }

Elements matching predicate

findAllParallel()

Elements that are true by Groovy truth

findParallel { }

First element matching predicate

findParallel()

First element that is true by Groovy truth

findAnyParallel { }

Any element matching (may be faster, no order guarantee)

grepParallel(filter)

Pattern match via isCase (Class, regex, Range, etc.)

grepParallel()

Elements that are true by Groovy truth

splitParallel { }

Partition into [matching, non-matching]

def adults = people.findAllParallel { it.age >= 18 }
def firstMatch = data.findParallel { it.isValid() }
def strings = mixed.grepParallel(String)
def (evens, odds) = numbers.splitParallel { it % 2 == 0 }

4.3. Iteration

Method Description

eachParallel { }

Side-effect iteration

eachWithIndexParallel { item, idx → }

Iteration with index

files.eachParallel { process(it) }
items.eachWithIndexParallel { item, idx -> println "$idx: $item" }

4.4. Predicates

Method Description

anyParallel { }

True if any element matches

anyParallel()

True if any element is true by Groovy truth

everyParallel { }

True if all elements match

everyParallel()

True if all elements are true by Groovy truth

countParallel { }

Count of matching elements

if (orders.anyParallel { it.isPriority() }) { ... }
assert positiveNumbers.everyParallel { it > 0 }
def errorCount = logs.countParallel { it.level == 'ERROR' }

4.5. Aggregation

Method Description

sumParallel()

Adds the elements, as sum() does

sumParallel { a, b → }

Reduce with binary operator

injectParallel(seed) { a, b → }

Reduce with seed (accumulator must be associative)

minParallel()

Minimum by natural ordering, as min()

minParallel { a, b → }

Minimum by comparator

maxParallel()

Maximum by natural ordering, as max()

maxParallel { a, b → }

Maximum by comparator

groupByParallel { }

Group into map by classifier

def total = amounts.sumParallel()
def joined = words.sumParallel { a, b -> a + ' ' + b }
def product = numbers.injectParallel(1) { a, b -> a * b }
def youngest = people.minParallel { a, b -> a.age <=> b.age }
def byDept = employees.groupByParallel { it.department }
injectParallel takes the identity value of an associative accumulator, matching Stream.reduce(identity, accumulator). A seed that is not an identity, or an accumulator that is not associative, does not match a sequential inject.

The no-argument forms behave as their sequential namesakes. sumParallel() calls plus on the left operand, as sum() does, so it matches sum() when plus is associative for the elements: integers, big decimals, strings and lists, but not floating-point values, whose rounding depends on the order of the additions. minParallel() and maxParallel() skip null elements and compare as Groovy’s < and > do, as min() and max() do. When several elements are equal, the minimum and maximum methods return the earliest.

A matching null from findParallel or findAnyParallel returns null, the same as no match. minParallel passes null elements to the comparator, matching sequential min(Comparator). maxParallel skips null elements, matching sequential max(Comparator): a collection of only nulls returns null without calling the comparator, and [null, 1] returns 1. A one-element collection does not call the comparator or the sumParallel operator. sumParallel returns a null reduction rather than throwing. groupByParallel keeps a null key, keys follow first-seen order, and each group stays in encounter order. A fork-join pool and Pool.virtual() agree on these results.

5. @Parallel for loops

The @Parallel annotation converts a for-in loop into a parallel operation with structured completion — all iterations finish before the next statement executes:

import groovy.transform.Parallel
import java.util.concurrent.CopyOnWriteArrayList

def results = new CopyOnWriteArrayList()

@Parallel
for (item in [1, 2, 3, 4, 5]) {
    results << item * 10
}

// All iterations complete before this line
assert results.sort() == [10, 20, 30, 40, 50]

Inside a ParallelScope.withPool block, @Parallel uses the bound pool:

ParallelScope.withPool(Pool.cpu()) { scope ->
    @Parallel
    for (n in data) {
        process(n)
    }
}

Under the hood, @Parallel rewrites the for loop body into a closure passed to eachParallel. This means the loop body is no longer a traditional loop — it is a closure invocation. The loop variable is also internally renamed (e.g., item becomes $parallel_item) to avoid scope conflicts in the generated code.

Because the body becomes a closure:

  • break and continue are not supported — they are not valid inside closures and will cause a compile error.

  • return inside the body returns from the closure (skipping the current iteration), not from the enclosing method.

Shared mutable state inside @Parallel loops must be thread-safe (e.g., AtomicInteger, CopyOnWriteArrayList, ConcurrentHashMap).
If you need the best debugging experience (e.g., stepping through loop bodies or inspecting variable names), consider using the *Parallel collection methods directly (such as eachParallel, collectParallel) instead of @Parallel, or be aware of the previously mentioned internal variable renaming.

6. Best Practices

6.1. Choosing between parallel collections and async/await

Parallel collections and @Parallel run on a ForkJoinPool with a small number of worker threads (typically matching your CPU core count). This is ideal for CPU-bound work — computation, transformation, aggregation — where each task keeps the CPU busy.

For I/O-bound or latency-bound work (network calls, database queries, sleeps, delays), use async/await with virtual threads instead. Virtual threads can scale to millions of concurrent tasks because blocking one doesn’t consume an OS thread.

Workload Right tool Why

CPU-bound (computation, parsing, math)

@Parallel, collectParallel, etc.

ForkJoinPool work-stealing maximises CPU utilisation

I/O-bound (HTTP calls, DB queries, file I/O)

async/await with virtual threads

Millions of concurrent waits without blocking OS threads

Mixed

async/await with Pool.io()

Virtual threads handle both compute and I/O

Value composition over a monadic carrier (Optional, Awaitable, Stream, …​)

DO comprehensions (groovy-macro-library)

Flattens nested flatMap/thenCompose chains into uniform name in source notation

To illustrate, consider processing 100 items where each involves a short delay (simulating I/O or latency):

// CPU-bound work — @Parallel is the right tool
@Parallel
for (item in bigList) {
    results << expensiveComputation(item)  // keeps CPU busy, no blocking
}
// I/O-bound work — async/await is the right tool
AsyncScope.withScope { scope ->
    urls.each { url ->
        scope.async { fetchUrl(url) }  // virtual thread blocks on I/O (free)
    }
}
// All fetches complete here — structured concurrency
// Anti-pattern — blocking on the common pool or Pool.cpu()/Pool.fixed(n)
@Parallel
for (item in 1..100) {
    Thread.sleep(50)    // blocks a ForkJoinPool worker!
    process(item)
}
// Only `parallelism` items run at once (about the core count on the
// common pool). The rest wait in the queue. If every worker blocks,
// a queued sibling can stall unless the pool has a spare thread.

On a fork-join pool the cap is the pool’s parallelism. Pool.fixed(n) stays at n threads. The same loop inside ParallelScope.withPool(Pool.virtual()) (JDK 21+) runs each iteration as its own task on that pool, so the waits are concurrent and the common pool is not involved. Keep CPU-bound loops on Pool.cpu() or Pool.fixed(n).

await Awaitable.delay(ms) inside a parallel collection body on a fork-join pool blocks that worker for the whole delay. Use async/await, or a Pool.virtual() / Pool.io() scope, for delay-based work.

6.2. Use thread-safe collections for shared state

The parallel body runs on multiple threads simultaneously. Use concurrent collections or atomics for any shared mutable state:

// Bad — ArrayList is not thread-safe
def results = []
items.eachParallel { results << transform(it) }  // race condition!

// Good — use CopyOnWriteArrayList or collectParallel
def results = items.collectParallel { transform(it) }