Can a nested ExecutorService run in parallel

840 Views Asked by At

Edit: Changed the title and reformatted my code: (Pleas bear with my questions, i am new to this parallel world)

Instead of using FJPool, i am using ExecutorService now to parallelize my tasks. All tasks and subtasks are independent and can run in parallel without any conflict. Here is my code snippet:

ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> someTask(args1);
executor.submit(() -> someTask(args2);
// Wait for tasks to complete and shutdown executor


private static void someTask( ... ) {
    ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    // executor runs a bunch of tasks in parallel here and then shutdown executor
}

My question is if i need to adjust number of thread pool since 2 tasks running in parallel try to create thread pool of the size of # of available cores? Will this work or will this block one of the initial task until we release the threads by shutting down?

===== Initial question =====

My question is slightly different that this question. I have 2 tasks, someTask1 and someTask2 which i am planning to parallelize. The problem is (i am not sure if this could be a problem or not) that someTask1 uses ForkJoinPool and runs a bunch of other tasks in parallel. Can I parallelize the 2 tasks someTask1 and someTask2 using ForkPoolJoin something like the code below even though one of the task i am parallelizing runs other tasks in parallel? If its possible can i get some help on refactoring the code below:

ForkPoolJoin forkJoinPool = new ForkJoinPool(parallelism);
if (someCond1) {
    forkJoinPool.submit(() -> someTask1( ... ));
}
if (someCond2) {
    forkJoinPool.submit(() -> someTask2( ... ));
}
// I want to wait here until forkJoinPool is done with both tasks (or either of the 1 based on each condition)?

private void someTask1( ... ) {
    ForkPoolJoin forkJoinPool = new ForkJoinPool(parallelism);
    try {
        forkJoinPool.submit(() -> someStream.stream().map( ... ))
                    .get(); // Wait for all the tasks to complete
    } finally {
        forkJoinPool.shutdown();
    }
}

Edit: I figured out a way to deal with the waiting issue. My solution is since i only have 2 tasks in parallel, i store the result of the forkJoinPool.submit into 2 Future variables and call on their get() function one by one. If someone else has a better more generic solution, that would be great.

0

There are 0 best solutions below