Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java ExecutorService Class

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:


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

  1. Set the Thread Pool Size Reasonably:

  2. CPU-bound tasks:线程数 = CPU 核心数 + 1
  3. IO-bound tasks:线程数 = CPU 核心数 * 2
  4. - CPU-bound tasks: `thread count = CPU cores + 1` - IO-bound tasks: `thread count = CPU cores * 2`
    1. Avoid Memory Leaks:

    2. Make sure to call shutdown() or shutdownNow() to shut down the thread pool.
    3. - Make sure to call `shutdown()` or `shutdownNow()` to shut down the thread pool.
      1. Handle Exceptions:

      2. Use try-catch Catch exceptions in tasks to prevent accidental thread termination.
      3. - Use `try-catch` to catch exceptions in tasks and prevent accidental thread termination.
        1. Use Future Manage Tasks:

        2. Pass Future.get() Obtain task results or check task status.
        3. - Use `Future.get()` to obtain task results or check task status.