Using a pool of threads
Each thread requires resources—the central processing unit (CPU) and memory. This means the number of threads must be controlled, and one way to do that is to create a fixed number of them—a pool. Besides, creating an object incurs an overhead that may be significant for some applications.
In this section, we will look into the Executor
interfaces and their implementations provided in the java.util.concurrent
package. They encapsulate thread management and minimize the time an application developer spends on writing code related to threads’ life cycles.
There are three Executor
interfaces defined in the java.util.concurrent
package, as follows:
- The base
Executor
interface: This has only onevoid execute(Runnable r)
method in it. - The
ExecutorService
interface: This extendsExecutor
and adds four groups of methods that manage the life cycle of worker threads and of the executor itself, as follows:submit()
methods,&...