Custom thread pool in Java 8 parallel stream

后端 未结 15 947
旧巷少年郎
旧巷少年郎 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:02

    Alternatively to the trick of triggering the parallel computation inside your own forkJoinPool you can also pass that pool to the CompletableFuture.supplyAsync method like in:

    ForkJoinPool forkJoinPool = new ForkJoinPool(2);
    CompletableFuture> primes = CompletableFuture.supplyAsync(() ->
        //parallel task here, for example
        range(1, 1_000_000).parallel().filter(PrimesPrint::isPrime).collect(toList()), 
        forkJoinPool
    );
    

提交回复
热议问题