Java ExecutorService Class
ExecutorService is a core interface in Java concurrent programming; it belongs to java.util.concurrent the package.
ExecutorService provides a higher-level thread management approach, allowing developers to efficiently execute asynchronous tasks without manually creating and managing threads.
The main roles of ExecutorService include:
- Thread pool management: Automatically manages the thread lifecycle, reducing the overhead of thread creation and destruction.
- Task scheduling: Supports submitting
RunnableorCallabletasks, and returnsFutureobjects to track task execution status. - Resource optimization: Improves system performance by reusing threads through the thread pool.
Core Methods of ExecutorService
ExecutorService provides various methods to submit, manage, and control task execution. The following are several key methods:
submit()
Used to submit a task (Runnable or Callable) and returns a Future object, so you can check whether the task is complete or obtain its return value.
Example
ExecutorService executor
=
Executors.
newFixedThreadPool
(
2
)
;
Future
future
=
executor.
submit
(
(
)
->
{
System
.
out
.
println
(
"Task is running"
)
;
}
)
;
execute()
Only used to submit Runnable tasks, returning no result.
Example
executor.
execute
(
(
)
->
{
System
.
out
.
println
(
"Task executed"
)
;
}
)
;
shutdown()
Gracefully shuts down the thread pool, no longer accepting new tasks, but waiting for submitted tasks to complete.
Example
executor.
shutdown
(
)
;
shutdownNow()
Immediately shuts down the thread pool, attempting to interrupt all executing tasks, and returns the list of unexecuted tasks.
Example
List
<
Runnable
notExecutedTasks
=executor.
shutdownNow
(
)
;
awaitTermination()
Waits for the thread pool to shut down until all tasks complete or a timeout occurs.
Example
executor.
awaitTermination
(
10
, TimeUnit.
SECONDS
)
;
How to Create an ExecutorService
Java provides the Executors utility class to create different types of thread pools:
newFixedThreadPool(int nThreads)
Creates a fixed-size thread pool, suitable for tasks with stable load.
Example
ExecutorService fixedThreadPool
=
Executors.
newFixedThreadPool
(
4
)
;
newCachedThreadPool()
Creates a cached thread pool, suitable for short-lived asynchronous tasks.
Example
ExecutorService cachedThreadPool
=
Executors.
newCachedThreadPool
(
)
;
newSingleThreadExecutor()
Creates a single-thread thread pool, suitable for sequentially executed tasks.
Example
ExecutorService singleThreadExecutor
=
Executors.
newSingleThreadExecutor
(
)
;
newScheduledThreadPool(int corePoolSize)
Creates a thread pool that supports scheduled or periodic tasks.
Example
ScheduledExecutorService scheduledThreadPool
=
Executors.
newScheduledThreadPool
(
2
)
;
Usage examples
Submit a Runnable Task
Example
ExecutorService executor
=
Executors.
newFixedThreadPool
(
2
)
;
executor.
submit
(
(
)
->
{
System
.
out
.
println
(
"Task 1 running"
)
;
}
)
;
executor.
submit
(
(
)
->
{
System
.
out
.
println
(
"Task 2 running"
)
;
}
)
;
executor.
shutdown
(
)
;
Submit a Callable Task and Get the Result
Example
ExecutorService executor
=
Executors.
newFixedThreadPool
(
2
)
;
Future
<
String
future
=executor.
submit
(
(
)
->
{
Thread
.
sleep
(
1000
)
;
return
"Task completed"
;
}
)
;
try
{
String
result
=
future.
get
(
)
;
// Block until the task completes
System
.
out
.
println
(
result
)
;
}
catch
(
Exception
e
)
{
e.
printStackTrace
(
)
;
}
executor.
shutdown
(
)
;
Best Practices
-
Set the Thread Pool Size Reasonably:
线程数 = CPU 核心数 + 1线程数 = CPU 核心数 * 2-
Avoid Memory Leaks:
shutdown() or shutdownNow() to shut down the thread pool.-
Handle Exceptions:
try-catch Catch exceptions in tasks to prevent accidental thread termination.-
Use
FutureManage Tasks:
Future.get() Obtain task results or check task status.