Custom parallelStream Thread pool

Introduction to the

Before we talked about the underlying use of ForkJoinPool to submit tasks. By default, ForkJoinPool creates a single thread for each processor. If parallelStream is not specified, Will use this shared thread pool to submit tasks.

What happens when we want to use a custom ForkJoinPool?

Usually the operation

If we want to do an addition from 1 to 1000, we can do this with a parallel stream:

List<Integer> integerList= IntStream.range(1.1000).boxed().collect(Collectors.toList());
        ForkJoinPool customThreadPool = new ForkJoinPool(4);

        Integer total= integerList.parallelStream().reduce(0, Integer::sum);
        log.info("{}",total);
Copy the code

Output result:


INFO com.flydean.CustThreadPool - 499500
Copy the code

Use a custom ForkJoinPool

The above example uses a shared Thread pool. Let’s see how we can use a custom thread pool to submit a parallel stream:

List<Integer> integerList= IntStream.range(1.1000).boxed().collect(Collectors.toList());

ForkJoinPool customThreadPool = new ForkJoinPool(4);
        Integer actualTotal = customThreadPool.submit(
                () -> integerList.parallelStream().reduce(0, Integer::sum)).get();
        log.info("{}",actualTotal);
Copy the code

In the above example, we defined a four-thread ForkJoinPool and used it to commit the parallelStream.

Output result:

INFO com.flydean.CustThreadPool - 499500
Copy the code

conclusion

If you do not want to use a common thread pool, you can use a custom ForkJoinPool for submission.

Examples of this article github.com/ddean2009/l…

Welcome to pay attention to my public number: procedures those things, more wonderful waiting for you! For more, visit www.flydean.com