How does the Executor framework in Java manage threads, and which factory methods matter in practice?
The Executor framework is a way of letting somebody else manage your threads.
You hand your tasks to an executor and it runs them on a pool of worker threads that it owns. The pool reuses the threads instead of making a new one for every task, so you do not pay the cost of starting a thread each time, and you can limit how many tasks run at the same moment.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
// A pool with four worker threads.
ExecutorService pool = Executors.newFixedThreadPool(4);
for (int index = 0; index < 8; index++) {
final int number = index;
pool.submit(new Runnable() {
public void run() {
System.out.println("task " + number + " is running");
}
});
}
pool.shutdown();
try {
pool.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
So which factory methods matter in practice? There are five that you will meet.
The method newFixedThreadPool gives you a pool with a fixed number of worker threads and a queue for the rest of the tasks. It is the right one for work that is on the processor.
The method newCachedThreadPool gives you a pool that grows when it needs to and shrinks back when it does not. It is the right one for tasks that wait a lot, such as calls to other services.
The method newSingleThreadExecutor gives you one worker thread, so the tasks run one after another in the order you gave them. It is the right one when the tasks have to be in order.
The method newScheduledThreadPool gives you a pool that can run a task later or over and over on a schedule.
The method newVirtualThreadPerTaskExecutor gives you a fresh virtual thread for every task, which is the modern answer to the same problem.
There is one trap with the first two, and it is worth knowing about. Both of them use a queue that has no limit, so if the tasks arrive faster than they are worked through, the queue grows and grows until the program runs out of memory. The fix is to build the pool yourself with a queue that has a limit and a rule for what to do when the queue is full.
The next question in this topic looks at shutting the pool down.