Is there any scenario for Executor instead of ExecutorService. Intention behind Executor interface?
Asked Answered
N

1

7

I am wondering if there is any reason to use an Executor instead of an ExecutorService.

As far as I know there is no implementation of the Executor interface in the JDK which is not also an ExecutorService which means you have to shut the service down so that there are no memory leaks. You cannot shut an Executor down but you can do that with an ExecutorService.

So, is there any scenario in which you would use something like that:

private final Executor _executor = Executors.newCachedThreadPool();

What is the intention behind the Executorinterface? Examples appreciated.

Neilson answered 8/3, 2019 at 8:40 Comment(0)
M
7

JavaDoc is your friend in this case

This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc

Further down you read

However, the Executor interface does not strictly require that execution be asynchronous. In the simplest case, an executor can run the submitted task immediately in the caller's thread:

 class DirectExecutor implements Executor {
     public void execute(Runnable r) {
         r.run();
     }
 }

These definitions are already expressive to me.

Regarding your usage example. Imho, no, I would never use this interface like that.
However it might be used as an accepted argument.

E.g. I want to run a task, but I'd like the user of my method to decide how this task is run.

public void run(final Executor taskExecutor) {
   taskExecutor.execute(this.myTaskRunnable);
}

The Executor implementation could be any behind the scene, it might be synchronous (like the example above) or asynchronous but I don't really care.
It's the user which will take care of handling it.

Moneylender answered 8/3, 2019 at 8:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.