Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExecutorService does not run tasks in parallel

I have a recursive bulk task that I put into execution in a ForkJoinPool thread pool.

public class SomeTask extends RecursiveAction {
    @Override
    protected void compute() {
       //Some recursive logic...
    }
}

public class Main {

    public static void main(String[] args) {
        startForkJoinPool();
    }

    private void startForkJoinPool() {
       SomeTask someTask = new SomeTask();

       ForkJoinPool pool = new ForkJoinPool(4);
       pool.invoke(someTask);
       pool.shutdown();
    }
}

Now I need to execute this logic in two more parallel threads.

I decided to try to use the ExecutorService thread pool, and when I put entities into it for execution, I found out that they are not executed in parallel, but, as it were, one of the threads is parked for the duration of the first one.

public class SomeTask extends RecursiveAction {
    @Override
    protected void compute() {
       //Some recursive logic...
    }
}

public class Main {

    public static void main(String[] args) {
        List<Thread> threadList = new ArrayList<>();
        threadList.add(new Thread(() -> startForkJoinPool()));
        threadList.add(new Thread(() -> startForkJoinPool()));

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        threadList.forEach(executorService::execute);
        executorService.shutdown();
    }

    private void startForkJoinPool() {
       SomeTask someTask = new SomeTask();

       ForkJoinPool pool = new ForkJoinPool(4);
       pool.invoke(someTask);
       pool.shutdown();
    }
}

Tell me, please, what can I do wrong? Many thanks in advance to anyone who can point me in the right direction.

like image 909
Kirill Avatar asked Dec 13 '25 13:12

Kirill


2 Answers

It is a bit strange that your code example contains ExecutorService.invoke and ExecutorService.execute where you should be calling ExecutorService.submit.

The ExecutorService documentation also contains a usage example. And then there is some nice Java Tutorial on the topic.

like image 94
Hiran Chaudhuri Avatar answered Dec 16 '25 01:12

Hiran Chaudhuri


Don't create any threads, that is the job of the ExecutorService.

You don't want to execute the task, you want to submit the task. Then you get a Future<T> returned.

As you already have a collection, consider invokeAll that returns List<Future<T>> and saves you iterating through your list.

like image 28
Bill Mair Avatar answered Dec 16 '25 02:12

Bill Mair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!