Java Threads & Concurrency API: Part 2
Creating Threads with ExecutorService
In Part I of this article, we discussed what threads are in Java, how to create them, the concept of a task, and the differences between using the
Let's delve a bit deeper into the Concurrency API, where Java introduced the
ExecutorService, which assists us in creating and managing threads.
ExecutorService is an interface in Java. To create an instance and utilize this interface, the Concurrency API offers a factory class called "Executors."
ExecutorServiceinterface reference variable.
Initialize it using
Executorsclass. Let us use the simplest one →
Create a task using
Runnableand pass it to a method called on the instance created in the above step.
Task is smallest unit of work performed by a Thread
ExecutorService - Main
You can see that all the tasks using a single thread executor are in order, whereas the one by the
Main thread follows no sequence as it’s a separate thread. Hence, results are guaranteed to be executed in the order in which they are added to the executor service (for single thread executor).
But…this guarantee vanishes when the number of threads increases so it’s better not to code relying on this behavior.
Shutting Down a Thread Executor
Executor thread creates a non-daemon thread and hence it is important to call
shutdown() method once you are finished using the service.
It doesn't implement AutoCloseable interface so we cannot use it with try-with-resources either.
Note: In the next article we will see how to use
submit() instead of
execute() and the advantage of doing so.
I hope you are enjoying the content I provide on my blog. As a passionate writer and dedicated software developer, I strive to create valuable and informative articles that resonate with you. Today, I would like to extend an invitation to support my work and help me continue producing high-quality content.
I have set up a Buy Me a Coffee page, a platform that allows readers like you to show their appreciation by making a small donation. Your contribution, no matter how big or small, goes a long way in supporting my efforts and keeping the blog running. You can also sponsor using the links at the bottom of this page.