Week 50 — What is an `Executor` (from `java.util.concurrent`) and how can it be used?
Question of the Week #50
What is an
Executor
(from java.util.concurrent
) and how can it be used?8 Replies
Executor
allows to submit tasks that are processed asynchronously.
There are different executors that run the tasks in thread pools. For example, Executors.newSingleThreadExecutor()
executes all submitted tasks in a single thread while Executors.newCachedThreadPool()
creates as many threads as needed.
For example, the following code submits to tasks to a single-threaded Executor
. It would first print println after submitting tasks
, wait one second, print Task 1
, wait another second and then print Task 2
.
Since both tasks are executed in the same thread, the second task needs to wait for the first task to finish.
Since virtual threads were introduced, a new executor,
Executors.newVirtualThreadPerTaskExecutor()
has been added. This executor creates a virtual thread for every submitted task.
If we use the above code with that executor, it would not wait one second between printing Task 1
and Task 2
:
📖 Sample answer from dan1st
An object that allows you to execute runnable tasks. Does not need to be asynchronous task either and provides away to decouple the tasks submissions.
Submission from smokeintitan
The executor runs runnables! We use it to keep the tricky work of “how to run” separate from “submitting something to run”. It lets us construct tasks as runnables, which we can then “merely” submit to the executor.
Submission from fm10esk
Executor
is an interface in the package java.util.concurrent
for higher level replacement for managing threads, other than directly manipulating Thread
objects.
CODE EXAMPLE:
Submission from cvs0.
Deals with initiation and also deals with controlling the execution of threads.
Submission from PNJ3.0#1519
The
Executor
from java.util.concurrent
package, is a interface which provides better replacement for managing and executing threads compared to Threads
in Java.
Another cool thing about it is, since it's a interface a it abstracts the details of thread creation, pooling, and lifecycle management which then again results in a more efficient development for big/concurrent applications
The actual purpose of the Executor
is to decouple task submission from the specifics of how each task will be run and lastly it then helps the developers to maintain the logic of their concurrent applications more than just focusing on minor details of the threads
How would one use Executor
, Lets get started with a Runnable task
Creating a executor service
Submitting Tasks
Lastly how to shutdown a executor
Submission from xenofic
⭐ Submission from pablohdz