Custom thread pool in Java 8 parallel stream

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

    There actually is a trick how to execute a parallel operation in a specific fork-join pool. If you execute it as a task in a fork-join pool, it stays there and does not use the common one.

    final int parallelism = 4;
    ForkJoinPool forkJoinPool = null;
    try {
        forkJoinPool = new ForkJoinPool(parallelism);
        final List primes = forkJoinPool.submit(() ->
            // Parallel task here, for example
            IntStream.range(1, 1_000_000).parallel()
                    .filter(PrimesPrint::isPrime)
                    .boxed().collect(Collectors.toList())
        ).get();
        System.out.println(primes);
    } catch (InterruptedException | ExecutionException e) {
        throw new RuntimeException(e);
    } finally {
        if (forkJoinPool != null) {
            forkJoinPool.shutdown();
        }
    }
    

    The trick is based on ForkJoinTask.fork which specifies: "Arranges to asynchronously execute this task in the pool the current task is running in, if applicable, or using the ForkJoinPool.commonPool() if not inForkJoinPool()"

提交回复
热议问题