Example of Custom Thread Pool Operation in Java8 Parallel Stream

  • 2021-07-24 10:59:10
  • OfStack

This article illustrates the custom thread pool operation in Java8 parallel flow. Share it for your reference, as follows:

1. Overview

java8 introduces the concept of flow, which is an effective way to perform a large number of operations on data. Parallel streams can be contained in an environment that supports concurrency. These streams can improve execution performance-at the expense of multithreading overhead

In this short article, we will look at the maximum limits of Stream API under 1 and how to make the parallel stream and thread pool instance (ThreadPool instance) 1 work under 1.

2. Parallel Stream Parallel Stream

Let's start with a simple example-calling on any Collection type parallelStream Method-it will return 1 possible parallel stream.


@Test
publicvoidgivenList_whenCallingParallelStream_shouldBeParallelStream(){
  List aList = newArrayList<>();
  Stream parallelStream = aList.parallelStream();
  assertTrue(parallelStream.isParallel());
}

The default processing flow for such a flow is to use the ForkJoinPool.commonPool() This is a thread pool shared by the entire application.

3. Customize the thread pool

When processing the flow, we can pass a custom thread pool. In the following example, we have a parallel stream that uses a custom thread pool to calculate the sum of 1 to 1,000,000:


@Testpublic void giveRangeOfLongs_whenSummedInParallel_shouldBeEqualToExpectedTotal() throws InterruptedException, ExecutionException { long firstNum = 1; long lastNum = 1_000_000; List aList = LongStream.rangeClosed(firstNum, lastNum).boxed()
   .collect(Collectors.toList());
  ForkJoinPool customThreadPool = new ForkJoinPool(4);
  long actualTotal = customThreadPool.submit(
   () -> aList.parallelStream().reduce(0L, Long::sum)).get();
  assertEquals((lastNum + firstNum) * lastNum / 2, actualTotal);
}

We use the construction method of ForkJoinPool and set the parallelism level to 4 to create a thread pool. To determine the optimal value (optimal) for different environments, we need to test 1. A good practice is to determine the value of parallel level based on the number of cores in your CPU.

4. Summary

We briefly looked at how to run parallel streams using a custom Thread Pool. As long as the appropriate level of parallelism is configured in the right environment, higher execution performance can be achieved under certain conditions.

For more readers interested in java related content, please check the topics on this site: "Summary of Java Process and Thread Operation Skills", "Java Data Structure and Algorithm Tutorial", "Summary of Java Operation Skills of DOM Node", "Summary of Java File and Directory Operation Skills" and "Summary of Java Cache Operation Skills"

I hope this article is helpful to everyone's java programming.


Related articles: