Tuesday, February 28, 2017

Difference between Executor, ExecutorService and Executers class in Java

All three classes Executor, ExecutorService, and Executers are part of Java's Executor framework which provides thread pool facilities to Java applications. Since creation and management of Threads are expensive and operating system also imposes restrictions on how many Threads an application can spawn, it's a good idea is to use a pool of thread to execute tasks in parallel, instead of creating a new thread every time a request comes in. This not only improves the response time of application but also prevent resource exhaustion errors like "java.lang.OutOfMemoryError: unable to create new native thread". A thread pool which is created when an application is a startup solves both of these problems. It has ready threads to serve clients when needed and it also has a bound on how many threads to create under load.

From Java 1.5, it was application programmer's responsibility to create and manage such thread pool but from JDK 5 onward Executor framework provides a variety of built-in thread pools in Java e.g. fixed thread pool which contains a fixed number of threads and cached thread pool which can spawn new threads when needed.

The main difference between Executor, ExecutorService, and Executors class is that Executor is the core interface which is an abstraction for parallel execution. It separates tasks from execution, this is different from java.lang.Thread class which combines both task and its execution. You can read the difference between Thread and Executor to learn more differences between these two key classes of Java.

On the other hand, ExecutorService is an extension of the Executor interface and provides a facility for returning a Future object and terminate, or shut down the thread pool. Once the shutdown is called, the thread pool will not accept new tasks but complete any pending task. It also provides a submit() method which extends Executor.execute() method and returns a Future.

The Future object provides the facility of asynchronous execution, which means you don't need to wait until the execution finishes, you can just submit the task and go around, come back and check if Future object has the result, if the execution is completed then it would have a result which you can access by using the Future.get() method. Just remember that this method is a blocking method i.e. it will wait until execution finish and the result is available if it's not finished already.

By using the Future object returned by ExecutorService.submit() method, you can also cancel the execution if you are not interested anymore. It provides cancel() method to cancel any pending execution.

Third one Executors is a utility class similar to Collections, which provides factory methods to create different types of thread pools e.g. fixed and cached thread pools. Let's see some more differences between these three classes.

And, if you are serious about mastering Java multi-threading and concurrency then I also suggest you take a look at the Java Multithreading, Concurrency, and Performance Optimization course by Michael Pogrebinsy on Udemy. It's an advanced course to become an expert in Multithreading, concurrency, and Parallel programming in Java with a strong emphasis on high performance.

Executor vs ExecutorService vs Executors in Java

As I told, all three classes are part of the Java 1.5 Executor framework and it's very important for a Java programmer to learn and understand these classes to make effective use of different types of thread pools provided by Java. Let's see some key differences between Executor, ExecutorService, and Executors in Java to understand them better:

1) One of the key differences between Executor and ExecutorService interface is that former is a parent interface while ExecutorService extends Executor i.e. it's a sub-interface of Executor.

2) Another important difference between ExecutorService and Executor is that Executor defines execute() method which accepts an object of the Runnable interface, while submit() method can accept objects of both Runnable and Callable interfaces.

3) The third difference between Executor and ExecutorService interface is that execute() method doesn't return any result, its return type is void but submit() method returns the result of computation via a Future object. This is also the key difference between submit() and execute() method, which is one of the frequently asked Java concurrency interview questions.

4) The fourth difference between ExecutorService and Executor interface is that apart from allowing a client to submit a task, ExecutorService also provides methods to control the thread pool e.g. terminate the thread pool by calling the shutDown() method. You should also read "Java Concurrency in Practice" to learn more about the graceful shutdown of a thread-pool and how to handle pending tasks.

Difference between Executor, ExecutorService and Executers class in Java

5) Executors class provides factory methods to create different kinds of thread pools e.g. newSingleThreadExecutor() creates a thread pool of just one thread, newFixedThreadPool(int numOfThreads) creates a thread pool of fixed number of threads and newCachedThreadPool() creates new threads when needed but reuse the existing threads if they are available.


Here is the summary of some key differences between Executor and ExecutorService in Java:

differences between Executor and ExecutorService in Java

That's all about the difference between Executor, ExecutorService, and Executors in Java. Remember, all three are part of the Executor framework. Java provides some out-of-box thread pool implementations e.g. pool of fixed number of threads and pool of cached thread which can expand itself depending upon load.

The ExecutorService class provides submit() method which can return the result of computation and Executor provides execute() method which accepts a task which can be executed by the same thread, a thread pool, or another thread depending upon implementation. You can further read "Java Concurrency in Practice" to learn more about thread-pools in Java. 

Further Learning
Multithreading and Parallel Computing in Java
Applying Concurrency and Multi-threading to Common Java Patterns
Java Concurrency in Practice Course by Heinz Kabutz


Ch!rag said...

Good to see such a detailed explanation. Thank you Javin.


Hi Javin ,

Nice artice , Just me add few things before we can wrap it up

1)Executor just executes stuff you give it.

ExecutorService adds startup, shutdown, and the ability to wait for and look at the status of jobs you've submitted for execution on top of Executor (which it extends).

2) Well in terms of Design Pattern , Executor interface is command pattern. Implementing execute() is obeying a Command

3) The difference is that execute simply starts the task without any further , whereas submit returns a Future object to manage the task. You can do the following things with the Future object:

Cancel the task prematurely, with the cancel method.
Wait for the task to finish executing, with get.

The Future interface is more useful if you submit a Callable to the pool. The return value of the call method will be returned when you call Future.get. If you don't maintain a reference to the Future, there is no difference

Unknown said...

hi very good article

Unknown said...

very informative article

Leonardo Labolida said...

Very good. Thanks.

Unknown said...

So for example newFixedThreadPool(5), will initially create 5 threads and reuses the same threads again and again correct?.. please correct me if i am wrong.

Unknown said...

Nice article

javin paul said...

Hello @Kranthi sama, you are right, fixed thread pool will reuse the thread and won't create new threads if there is more load. If you want dynamic resizing of thread pool then you can use cached thread pool, which creates new threads based upon work.

javin paul said...

Thank you @malikarjun, please share with your friends too.

Aatif said...

Executor & ExecutorService are interfaces not classes. Correction is needed. It's confusing.!

Pravin said...

Hello Javin Sir,
May i know please is this question's relevant to 1 year exp candidate also?
Please Replay.

javin paul said...

Hello Pravin, chances are less but you never know. Though, I suggest you first go through the list 50+ Basic Java Interview Questions, which is more relevant to 1 year experience candidate. All the best.

Post a Comment