Artem Petrov
Artem Petrov

Reputation: 802

Is it beneficial to use ForkJoinPool as usual ExecutorService

Let's say I have a code like that:

class Foo {
    private final ExecutorService executor;

    public Foo(ExecutorService executor) {
        this.executor = executor;
    }

    public void doSomething() {
        executor.execute(() -> {/* Do important task */});
    }
}

Can I gain better performance if instead of passing ThreadPoolExecutor in constructor I use ForkJoinPool. If yes then why and should I prefer use it in any circumstances instead of ThreadPoolExecutor.

Update 1

My question is about usage of ForkJoinPool through ExecutorService API and doesn't suppose recursive task splitting using ForkJoinPool specific API.

Upvotes: 2

Views: 2307

Answers (2)

Ravindra babu
Ravindra babu

Reputation: 38910

It will be effective if you use newWorkStealingPool

public static ExecutorService newWorkStealingPool()

Creates a work-stealing thread pool using all available processors as its target parallelism level.

You can find advantage from this documentation page:

A ForkJoinPool provides the entry point for submissions from non-ForkJoinTask clients, as well as management and monitoring operations.

A ForkJoinPool differs from other kinds of ExecutorService mainly by virtue of employing work-stealing: all threads in the pool attempt to find and execute tasks submitted to the pool and/or created by other active tasks (eventually blocking waiting for work if none exist).

This enables efficient processing when most tasks spawn other subtasks (as do most ForkJoinTasks), as well as when many small tasks are submitted to the pool from external clients. Especially when setting asyncMode to true in constructors, ForkJoinPools may also be appropriate for use with event-style tasks that are never joined.

Upvotes: 1

Mikita Harbacheuski
Mikita Harbacheuski

Reputation: 2253

Yes you can if you have recursive non-blocking tasks.

Here is great explanation from Cay S. Horstmann from recent Joker conference.

Upvotes: 2

Related Questions