ExecutorService and thread pools
Java’s ExecutorService is a mechanism for executing tasks asynchronously. As a part of the java.util.concurrent package, ExecutorService is an interface used to manage and control thread execution in a multithreaded environment. We have seen so far how we can manually control threads, and we’ll now see how we can use ExecutorService instead. We’ll see the details of ExecutorService and its implementations, such as SingleThreadExecutor and ScheduledExecutorService. Let’s see SingleThreadExecutor first.
Executing tasks using SingleThreadExecutor
Firstly, let’s start with SingleThreadExecutor. This ExecutorService has one single worker thread to process tasks, guaranteeing that tasks are executed in the order they’re submitted. It’s useful when we need sequential execution.
Consider a scenario with an election where votes are being counted. To mimic this process, we’ll represent each vote...