OiO.lk Blog java Wrapping Stream.parallel() by Executor service in Java
java

Wrapping Stream.parallel() by Executor service in Java


I’m studying Java Core on course DMDEV in Udemy and YouTube. On Level 2 in lessons Concurrent I probably saw mistake in code the tutor was made. But my question to him was still without response. So maybe experts here can help.

Task: there is an array with 1_000_000 elements filled with random int in range from 1 to 300. Write code in Java to find maximum element by using 10 threads.

The teacher proposed this solution:

public class TaskFromDmdevForSOF {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        int[] values = new int[1_000_000];
        Random random = new Random();
        for (int i = 0; i < values.length; i++) {
            values[i] = random.nextInt(300) + 1;
        }

        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        int max = findMaxParallel(values, threadPool);
        System.out.println(max);
        threadPool.shutdown();
        threadPool.awaitTermination(1, TimeUnit.MINUTES);
    }
    private static int findMaxParallel(int[] values, ExecutorService executorService) throws ExecutionException, InterruptedException {
        return executorService.submit(() -> IntStream.of(values)
                .parallel()
                .max()
                .orElse(Integer.MIN_VALUE)).get();
    }
}

But I was curious, is it real 10 threads working under this task?
I added .peek() after .parallel() and saw that there is a common ForkJoinPool with 4 threads working under hood.
To my mind we need to use new ForkJoinPool(10) instead of Executors.newFixedThreadPool(10) to guarantee that there are real 10 threads working.
Or better we need to implement our own class from extending RecursiveTask to solve this task properly.
Am I right? Thanks a lot for yours answers.



You need to sign in to view this answers

Exit mobile version