Custom thread pool in Java 8 parallel stream

后端 未结 15 946
旧巷少年郎
旧巷少年郎 2020-11-22 00:15

Is it possible to specify a custom thread pool for Java 8 parallel stream? I can not find it anywhere.

Imagine that I have a server application and I would like to

15条回答
  •  星月不相逢
    2020-11-22 01:16

    If you don't mind using a third-party library, with cyclops-react you can mix sequential and parallel Streams within the same pipeline and provide custom ForkJoinPools. For example

     ReactiveSeq.range(1, 1_000_000)
                .foldParallel(new ForkJoinPool(10),
                              s->s.filter(i->true)
                                  .peek(i->System.out.println("Thread " + Thread.currentThread().getId()))
                                  .max(Comparator.naturalOrder()));
    

    Or if we wished to continue processing within a sequential Stream

     ReactiveSeq.range(1, 1_000_000)
                .parallel(new ForkJoinPool(10),
                          s->s.filter(i->true)
                              .peek(i->System.out.println("Thread " + Thread.currentThread().getId())))
                .map(this::processSequentially)
                .forEach(System.out::println);
    

    [Disclosure I am the lead developer of cyclops-react]

提交回复
热议问题