Class ParallelCollectionExtensions

java.lang.Object
org.codehaus.groovy.runtime.ParallelCollectionExtensions

public class ParallelCollectionExtensions extends Object
DGM-like extension methods that add parallel collection operations to Collection.

These methods use Pool.current() to obtain the current pool (typically set by ParallelScope.withPool(int, java.util.function.Function<groovy.concurrent.AsyncScope, T>)). If no pool is current, they use ForkJoinPool.commonPool().

A fork-join pool (Pool.fixed(int), Pool.cpu(), ParallelScope.withPool(int, Function), or the common pool) runs a Java parallel stream on that pool. Parallelism is a hard cap: callbacks are not wrapped in managedBlock, so CPU-bound work does not create spare workers, and the common pool is not enlarged. A blocking callback can stall that pool when every worker blocks while a sibling task is still queued. Size a fork-join pool to at least one more thread than the number of concurrent blockers, or use a pool that is not a fork-join pool for waiting work.

Pool.virtual(), and Pool.io() when virtual threads are available, are not fork-join pools. The operation then submits one task per element to that pool. Blocking callbacks stay on the caller's pool instead of falling back to the common pool. Before virtual threads, Pool.io() is a fixed fork-join pool and has the same cap as Pool.fixed(int). CPU-bound work should stay on Pool.fixed(int) or Pool.cpu().

A nested operation stays on the same pool. A worker created for a pool carries that pool, and Pool.current() reports it when the thread has no explicit binding, so a callback does not rebind the pool on each element. On a bounded executor that does not create extra threads, the nested operation runs on the worker already executing the outer callback. That worker would otherwise wait for a task queued behind it. Pool.virtual() still submits one task per element.

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

A matching null element, a null reduction, and a null group key are preserved on a fork-join pool and on an executor pool. An empty search or reduction returns null. maxParallel skips null elements, matching sequential max(Comparator). minParallel passes nulls to the comparator, matching sequential min(Comparator).

Inspired by GPars' GParsPoolUtil category methods.

Since:
6.0.0
  • Constructor Details

    • ParallelCollectionExtensions

      public ParallelCollectionExtensions()
  • Method Details

    • eachParallel

      public static <T> void eachParallel(Collection<T> self, Consumer<T> action)
      Iterates over the collection in parallel, applying the action to each element.
    • collectParallel

      public static <T, R> List<R> collectParallel(Collection<T> self, Function<T,R> transform)
      Transforms each element in parallel, returning a new list.
    • collectManyParallel

      public static <T, E> List<T> collectManyParallel(Collection<E> self)
      Flattens a collection of collections into a list, in parallel, as sequential collectMany() does. Outer encounter order is preserved, as is the order inside each element collection. An element that is not a collection fails as it does sequentially.
       assert [[1, 2], [3], []].collectManyParallel() == [1, 2, 3]
       
      Since:
      6.0.1
    • findAllParallel

      public static <T> List<T> findAllParallel(Collection<T> self, Predicate<T> filter)
      Filters the collection in parallel, returning elements that match.
    • findAllParallel

      public static <T> List<T> findAllParallel(Collection<T> self)
      Returns the elements that are true according to Groovy truth, in parallel, as sequential findAll() does. Encounter order is preserved.
       assert [1, 0, null, 'a', '', [2], []].findAllParallel() == [1, 'a', [2]]
       
      Since:
      6.0.1
    • findParallel

      public static <T> T findParallel(Collection<T> self, Predicate<T> filter)
      Finds the first element matching the predicate in encounter order. Although evaluation happens in parallel, the result is the matching element with the lowest index. A matching null and no match both return null. Use findAnyParallel(java.util.Collection<T>, java.util.function.Predicate<T>) if any match will do — it may be faster as it avoids ordering constraints.
    • findParallel

      public static <T> T findParallel(Collection<T> self)
      Finds the first element that is true according to Groovy truth, in encounter order, as sequential find() does. No match returns null.
       assert [null, 0, '', 42, 43].findParallel() == 42
       
      Since:
      6.0.1
    • findAnyParallel

      public static <T> T findAnyParallel(Collection<T> self, Predicate<T> filter)
      Finds any element matching the predicate. May be faster than findParallel(java.util.Collection<T>, java.util.function.Predicate<T>) as it does not preserve encounter order. A matching null and no match both return null.
    • anyParallel

      public static <T> boolean anyParallel(Collection<T> self, Predicate<T> predicate)
      Returns true if any element matches the predicate.
    • anyParallel

      public static <T> boolean anyParallel(Collection<T> self)
      Returns true if any element is true according to Groovy truth, as sequential any() does.
       assert [0, null, 'a'].anyParallel()
       assert ![0, null, ''].anyParallel()
       
      Since:
      6.0.1
    • everyParallel

      public static <T> boolean everyParallel(Collection<T> self, Predicate<T> predicate)
      Returns true if all elements match the predicate.
    • everyParallel

      public static <T> boolean everyParallel(Collection<T> self)
      Returns true if every element is true according to Groovy truth, as sequential every() does. An empty collection returns true.
       assert [1, 'a', [2]].everyParallel()
       assert ![1, 0].everyParallel()
       
      Since:
      6.0.1
    • countParallel

      public static <T> long countParallel(Collection<T> self, Predicate<T> predicate)
      Counts elements matching the predicate.
    • minParallel

      public static <T> T minParallel(Collection<T> self)
      Finds the minimum element by natural ordering, as sequential min() does: null elements are skipped, elements compare as Groovy's < does (so numbers of different types compare by value), and the earliest of equal elements is returned. An empty collection, or one of only nulls, returns null.
       assert [4, null, 2.5, 3G].minParallel() == 2.5
       
      Since:
      6.0.1
    • minParallel

      public static <T> T minParallel(Collection<T> self, Comparator<T> comparator)
      Finds the minimum element using the given comparator. When several elements compare equal, the earliest in encounter order is returned. An empty collection returns null. A one-element collection returns that element, including null, without calling the comparator.

      Null elements are passed to the comparator, matching sequential min(Comparator). maxParallel(java.util.Collection<T>) skips nulls instead, matching sequential max(Comparator).

    • maxParallel

      public static <T> T maxParallel(Collection<T> self)
      Finds the maximum element by natural ordering, as sequential max() does: null elements are skipped, elements compare as Groovy's > does (so numbers of different types compare by value), and the earliest of equal elements is returned. An empty collection, or one of only nulls, returns null.
       assert [4, null, 2.5, 3G].maxParallel() == 4
       
      Since:
      6.0.1
    • maxParallel

      public static <T> T maxParallel(Collection<T> self, Comparator<T> comparator)
      Finds the maximum element using the given comparator. When several elements compare equal, the earliest in encounter order is returned. An empty collection returns null. A one-element collection returns that element, including null, without calling the comparator.

      Null elements are skipped, matching sequential max(Comparator). A collection of only nulls returns null and does not call the comparator. minParallel(java.util.Collection<T>) passes nulls through, matching sequential min(Comparator).

    • sumParallel

      public static <T> T sumParallel(Collection<T> self, BinaryOperator<T> accumulator)
      Reduces the collection in parallel using the given operator. The operator must be associative. An empty collection returns null. A one-element collection returns that element, including null, without calling the operator. A null operator result is returned as null.
    • sumParallel

      public static Object sumParallel(Collection<?> self)
      Adds the elements together in parallel, as sequential sum() does: each addition calls plus on the left operand. An empty collection returns null, and a one-element collection returns that element without calling plus.

      The result matches sum() only when plus is associative for the elements. It is for integers, big decimals, strings and lists, but floating-point addition rounds, so a parallel sum of float or double values can differ from sum() in the last digits.

       assert [1, 2, 3, 4].sumParallel() == 10
       assert ['a', 'b', 'c'].sumParallel() == 'abc'
       
      Since:
      6.0.1
    • groupByParallel

      public static <T, K> Map<K,List<T>> groupByParallel(Collection<T> self, Function<T,K> classifier)
      Groups elements by the classifier function in parallel. A null key is kept. Keys follow first-seen order, and within each group elements stay in encounter order.
    • eachWithIndexParallel

      public static <T> void eachWithIndexParallel(Collection<T> self, BiConsumer<T,Integer> action)
      Iterates over the collection in parallel with element indices. Index assignment is based on the collection's iteration order, but execution order is not guaranteed.
    • collectManyParallel

      public static <T, R> List<R> collectManyParallel(Collection<T> self, Function<T,? extends Collection<R>> transform)
      Transforms each element into a collection and flattens the results in parallel (parallel flatMap). Outer encounter order is preserved, as is the order inside each returned collection.
    • splitParallel

      public static <T> List<List<T>> splitParallel(Collection<T> self, Predicate<T> predicate)
      Partitions the collection into two lists: elements that match the predicate and elements that don't. Both lists keep encounter order.
      Returns:
      a list of two lists: [matching, non-matching]
    • injectParallel

      public static <T> T injectParallel(Collection<T> self, T seed, BinaryOperator<T> accumulator)
      Reduces the collection in parallel with an identity value.

      seed is the identity of accumulator, and the accumulator must be associative. This matches Stream.reduce(identity, accumulator): a parallel execution may apply seed once per chunk and then combine the chunks. A seed that is not an identity does not match a sequential inject. An empty collection returns seed.

      Parameters:
      seed - the identity value of accumulator
      accumulator - an associative reduction function
    • grepParallel

      public static <T> List<T> grepParallel(Collection<T> self, Object filter)
      Filters elements using Groovy's isCase pattern matching in parallel. Supports the same filter types as Groovy's grep: Class, regex Pattern, Range, Collection, Closure, etc. Encounter order is preserved. A null filter is allowed and matches the same elements as sequential grep(null). An element is kept when isCase is Groovy-true, not only when it returns Boolean.TRUE.
      Parameters:
      filter - the pattern to match against (uses isCase); may be null
    • grepParallel

      public static <T> List<T> grepParallel(Collection<T> self)
      Returns the elements that are true according to Groovy truth, in parallel, as sequential grep() does. Encounter order is preserved.
       assert [1, 0, null, 'a', ''].grepParallel() == [1, 'a']
       
      Since:
      6.0.1