Does simply calling parallelStream run the tasks in parallel?

Lucas Noetzold :

I've seen a bunch of examples on the internet that, in order to use the streams API to do parallel stuff, just call the .parallelStream() method like this:

mySet
    .parallelStream()
    ... // do my fancy stuff and collect

But in other cases I've seen the parallel stream being used inside a thread pool submition, like this:

ForkJoinPool.commonPool().submit(() -> {
    mySet
        .parallelStream()
        ... // do my fancy stuff and collect
})

Does just calling parallelStream() executes whatever comes next in multiple concurrent threads? Like in some pre-configured thread pool or something. Or do I have to create my threads and then use the parallel stream?

Eugene :

Yes parallelStream runs things in parallel.

Usually when there is a long running stream in parallel you do not want to run that on the commonPool because all other parallel streams are using that too.

This btw is an implementation detail, since stream do not specify what pool they will use for parallel processing, but under the current implementation you should not use ForkJoinPool.commonPool(), but instead create a new pool:

ForkJoinPool pool = new ForkJoinPool(2);

pool().submit(() -> {
mySet
    .parallelStream()
    ... // do my fancy stuff and collect
})

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=68404&siteId=1