Thread pools
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 the writing code related to threads' life cycles.
There are three Executor
interfaces defined in the java.util.concurrent
package:
- The base
Executor
interface has only onevoid execute(Runnable r)
method in it. It basically replaces the following:
Runnable r = ...; (new Thread(r)).start()
However, we can also avoid a new thread creation by getting it from a pool.
- The
ExecutorService
interface extendsExecutor
and adds four groups of methods that manage the life cycle of the worker threads and of the executor itself: - Methods
submit()
: Place in the queue for the execution of an object of the interfaceRunnable
or interfaceCallable
(allows the worker thread to return a value); return object ofFuture
interface, which can be used to access the value returned by the...