Custom thread pool in Java 8 parallel stream

后端 未结 15 907
旧巷少年郎
旧巷少年郎 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条回答
  •  -上瘾入骨i
    2020-11-22 00:57

    Here is how I set the max thread count flag mentioned above programatically and a code sniped to verify that the parameter is honored

    System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "2");
    Set threadNames = Stream.iterate(0, n -> n + 1)
      .parallel()
      .limit(100000)
      .map(i -> Thread.currentThread().getName())
      .collect(Collectors.toSet());
    System.out.println(threadNames);
    
    // Output -> [ForkJoinPool.commonPool-worker-1, Test worker, ForkJoinPool.commonPool-worker-3]
    

提交回复
热议问题