Sunday, September 17, 2023

Difference between Executor, ExecutorService and Executers class in Java

All three classes Executor, ExecutorService, and Executors are part of Java's Executor framework which provides thread pool facilities to Java applications. Since the creation and management of Threads are expensive and the operating system also imposes restrictions on how many Threads an application can spawn, it's a good idea is to use a pool of threads 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 the application but also prevent resource exhaustion errors like "java.lang.OutOfMemoryError: unable to create new native thread".

A thread pool that 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 the 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 also 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 the 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 a cancel() method to cancel any pending execution.

The 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 Pogrebinsky 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.

Difference between Executor, ExecutorService and Executers class in Java



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 the former is a parent interface while ExecutorService extends Executor I mean, 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 the execute() method doesn't return any result, its return type is void but the 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 a fixed number of threads, and newCachedThreadPool() creates new threads when needed but reuse the existing threads if they are available.

Summary

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 like, a pool of fixed number of threads and pool of cached thread which can expand itself depending upon load.

The ExecutorService class provides the submit() method which can return the result of computation and Executor provides the 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 check out these online courses to learn more about thread-pools and other essential concurrency concepts in Java. 


Other Java Multithreading Articles you may like
  • The Complete Java Developer RoadMap (roadmap)
  • What is happens-before in Java Concurrency? (answer)
  • 10 Free Java Courses for Beginners and Intermediate developers (courses)
  • How to avoid deadlock in Java? (answer)
  • 10 Java Multithreading and Concurrency Best Practices (article)
  • Understanding the flow of data and code in Java program (answer)
  • Top 50 Multithreading and Concurrency Questions in Java (questions)
  • Top 5 Books to Master Concurrency in Java (books)
  • Is Java Concurrency in Practice still valid (answer)
  • Difference between CyclicBarrier and CountDownLatch in Java? (answer)
  • How Happens Before works in Java?  (answer)
  • 10 Tips to become a better Java Developer  (tips)
  • How to do inter-thread communication in Java using wait-notify? (answer)
  • Top 5 Courses to Learn Java Multithreading in-depth (courses)

Thanks for reading this article of far. If you find this Executor vs ExecutorService vs Executors comparison then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note. 

P. S. - If you are new to the Java world and want to learn essential topics like multithreading and concurrency and looking for some free courses to start with then you can also check out this best free Java Multithreading courses on Udemy. It is a good free course to learn  Java Concurrency as well.

Now, over to you, what is difference between ExecutorService and ForkJoinPool in Java? Which one would you prefer if you have to sort 10 million numbers in Java?

14 comments :

Ch!rag said...

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

SARAL SAXENA said...

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.

Mallikarjun 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.

kc said...

Kindly Make correction.

Executors is a class
Executor in an exterface
ExecutoService is also an interface which extends Executor interface.

Karthik said...

Great explanation! Thanks!

Post a Comment