3
List<Integer> list = Arrays.asList(3, 4, 6, 1, 2, 3, 5, 6);  
list.parallelStream().forEach(System.out::print);        
list.parallelStream().map(a -> a + 2).forEach(a -> System.out.println(Thread.currentThread().getName() + "--" + a));

two and three line will use a same forkjoinpool? if not, how to let them use one?

Misha
  • 27,433
  • 6
  • 62
  • 78
twogoods
  • 1,646
  • 2
  • 14
  • 21

2 Answers2

1

All parallels streams run in the singleton pool returned by ForkJoinPool.commonPool(). The exception is if you run a parallel stream from inside a ForkJoinPool, the stream will run within the pool from which is it invoked.

These are implementation details that aren't specified anywhere in the Streams API documentation, so java devs would be perfectly within their right to pick some other pool or eschew fork/join framework entirely and do something else.

If it is crucial for you to know which threads end up executing your code, streams API might not be your best choice.

Misha
  • 27,433
  • 6
  • 62
  • 78
0

At the moment - yes, there is a single pool for all parallel streams by default - it's ForkJoinPool#commonPool; thus your observation is right.

There is a way to set-up a custom pool for each execution of a Stream pipeline, see here.

It would look like this for your second example:

    List<Integer> list = Arrays.asList(3, 4, 6, 1, 2, 3, 5, 6);

    ForkJoinPool forkJoinPool = new ForkJoinPool(4);
    ForkJoinTask<?> task = forkJoinPool.submit(() -> list
            .parallelStream()
            .map(a -> a + 2)
            .forEach(a -> System.out.println(Thread.currentThread().getName() + "--" + a)));
    task.get();
Eugene
  • 117,005
  • 15
  • 201
  • 306