Introduction
Since Java 5, it is encouraged to use an executorService instead of using the Thread class directly. The executorService provides an easy-to-use API to submit tasks to a pool of threads.
Creating an instance of ExecutorService
Java provides multiple implementations of the ExecutorService interface. The Executors class has Factory and utility methods to create an instance of an ExecutorService. The following code snippet shows you how to create instances of the different ExecutorService implementations with a short description.
| |
Using an ExecutorService
ExecutorService methods take a Runnable or Callable as a parameter. The threads inside the pool of the ExecutorService will run
these tasks. In the following examples, I will show you how to submit tasks to an ExecutorService in multiple ways. The examples
use a newFixedThreadPool, but you can use any executorService you need.
Execute a runnable
The execute method will run the task in a new thread. This is a fire-and-forget method, as we don't have anything to check or control the thread.
| |
Submitting a runnable
In the following example, we submit() a Runnable to the executorService. This will return an instance of Future. We can use this instance to check if the thread is done and to wait for the result using get().
| |
Submitting a callable
In the following example, we submit() a callable to the executorService. This will return an instance of Future. We can use this instance to check if the thread is done and to wait for the result using get(). In this case, the result is of type String.
| |
Using ExecutorService invokeAll
With invokeAll(), we can submit a number of tasks with one call. Using the list of Future instances, we can wait till all the threads are done. In the following example, you can see how to use the invokeAll method.
| |
Using ExecutorService invokeAny
With invokeAny() we can submit a number of threads. The result of the first task that is done will be returned. In the following example, I submit three callables of type String. The invokeAny() returns the String value of the first callable to finish.
| |
How to use the ScheduledExecutorService
With ScheduledExecutorService, you can schedule tasks to run in the future or to repeat a certain thread periodically.
Schedule a task to run once
With schedule() you schedule a task to run once in the future. It takes a callable, long, and time-unit as a parameter. With the second and third parameter, you can set the delay, after which the task will run. In the following example the task will start after 5 minutes.
| |
Schedule a task to run at a fixed rate
With scheduleAtFixedRate, you start a task after every number of the time-unit that you choose. The first parameter is the Runnable that will run. The second parameter is the initial delay of the first time the task will run. The second Long is the time between starting the current task and the next one. The last parameter is the time unit you need.
In the following example, we run the first task after waiting one minute. After the initial delay, we will start a new task every two minutes.
| |
Schedule a task to run at a delay
With scheduleWithFixedDelay we can set a task to repeat multiple times. The first parameter is the runnable we want to run. The second parameter is the initial delay. The third parameter is the time between finishing the previous task and starting the next one. The last parameter is the time unit you need.
In the following example, we start a thread after waiting one minute. We then wait till the previous task is done plus two minutes before starting the next task.
| |
Shutdown an ExecutorService
Shutting down an ExecutorService is kind of tricky. The best way to do so can be found inside the Java documentation. In the following code snippet, you can also find the code from the documentation to shut down an ExecutorService.
| |
Shutdown ExecutorService in Java 19
With Java 19, the ExecutorService implements the autocloseable interface. This makes it a lot easier to shut down an ExecutorService. In the following example, you can see how we do this. Before you would exit the try Java will close the ExecutorService for you. This is a great improvement. Do keep in mind that in the worst case it will await termination for 1 day.
| |
Conclusion
In this article, we saw how to use the ExecutorService and submit tasks to the underlying thread pool.
Further reading
- How to enable virtual threads in Java 19
- Structured concurrency in Java with Loom
- Creating Virtual Threads
Adopt Virtual Threads & Structured Concurrency Without Production Surprises
Virtual threads look simple on paper—until carrier thread pinning, unmounted stack heap pressure, or legacy ThreadLocals hit production. Bring me in for a tailored 1-day Java Virtual Threads, Structured Concurrency & Scoped Values Workshop built around your team's actual architecture and frameworks.
Want More Deep-Dive JVM Benchmarks & Project Panama Research?
Follow my weekly engineering posts on LinkedIn, explore the full JMH benchmark suites and pure-Java Linux io_uring / FUSE projects on GitHub, or download my conference talk slides: