java parallel stream is using same worker

Viewed 224

This is my code:

    list.stream()
        .parallel()
        .map(cpcP -> this.myDao.myOperation(cip, cpcP))
        .collect(Collectors.toList());

Inside myOperation I've written a log:

log.debug("{} -> {}", Thread.currentThread().getName(), ...);

I'm getting those logs:

ForkJoinPool.commonPool-worker-3 -> ...
ForkJoinPool.commonPool-worker-3 -> ...
ForkJoinPool.commonPool-worker-3 -> ...
ForkJoinPool.commonPool-worker-3 -> ...
ForkJoinPool.commonPool-worker-3 -> ...
ForkJoinPool.commonPool-worker-3 -> ...
ForkJoinPool.commonPool-worker-3 -> ...
ForkJoinPool.commonPool-worker-3 -> ...
...

It seems it is always using the same thread.

Any ideas?

1 Answers

Aside the comments that indicate the common thread pool could be busy with other operations in parallel, a couple of other reasons:

  1. you have the system property java.util.concurrent.ForkJoinPool.common.parallelism to 1, explicitly limiting the parallelism of the pool to 1.

  2. The number of cores is very small (either 1 or 2), since the common pool uses Runtime.getRuntime().availableProcessors() - 1 as the parallelism.

Related