Location>code7788 >text

Interviewer: tell us about the execution process of stopping the thread pool?

Popularity:864 ℃/2024-09-19 11:51:04

For the thread pool we are using, ThreadPoolExecutor, there are two ways to stop the thread pool:

  1. shutdown(): Gracefully closes the thread pool, i.e., it no longer accepts new tasks, but waits for submitted tasks (both those that are executing and those waiting in the queue) to finish executing.Wait for all tasks to be executed before the thread pool enters the terminated state
  2. shutdownNow(): Attempts to stop all executing tasks and returns a list of tasks waiting to be executed.Ongoing tasks may be interruptedApplicable toA situation where you need to stop the thread pool immediately, but don't care if the task being executed completes immediately.

1.Code Demo

Let's take a look at the use of the shutdown() and shutdownNow() methods in the following code examples.

1.1 Shutdown() Method Execution

We set the core of the thread pool and the maximum number of threads to 2, the task queue can store 10 tasks, we add 5 tasks at once, each task is executed for more than 2s, we execute the stop method after adding the task, and try to add another new task after 1s, as shown in the following code:

import ;
import ;
import ;
import ;

public class ThreadPoolExecutorShutdownTest {
    public static void main(String[] args) {
        // Creating Threads
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2,
                2,
                1000,
                ,
                new ArrayBlockingQueue<Runnable>(10),
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        ("Enforcement of denial policies");
                    }
                });
        // Add Tasks
        for (int i = 0; i < 5; i++) {
            (() -> {
                String tName = ().getName();
                (tName + ":Commencement of tasks!");
                try {
                    (2000);
                } catch (InterruptedException e) {
                    ();
                }
                (tName + ":Closure of the mandate!");
            });
        }
        // Stop Thread
        ();
        try {
            (1000);
        } catch (InterruptedException e) {
            ();
        }
        // Add a new task
        (() -> ("The last new mission"));
    }
}

The results of the execution of the above program are as follows:

It is clear from the above results thatAfter executing the shutdown() method, the program waits for all tasks in the thread pool to finish executing before shutting down, during which time the thread pool rejects the addition of new tasks and calls the thread pool's rejection policy.

1.2 shutdownNow() method implementation

If the shutdown() method is replaced by the shutdownNow() method, the result of the above program is as follows:

In other words.After the shutdownNow() method is called, executing tasks are stopped immediately and any tasks in the task queue that are not executing are cleared. New tasks added after the shutdownNow() method is called are rejected and the thread pool's rejection policy is enforced.

(workflow

The shutdown() method executes as follows:

public void shutdown() {
    final ReentrantLock mainLock = ;
    ();
    try {
        checkShutdownAccess();
        advanceRunState(SHUTDOWN);
        interruptIdleWorkers();
        onShutdown(); // hook for ScheduledThreadPoolExecutor
    } finally {
        ();
    }
    tryTerminate();
}

The source code execution flow is as follows:

  1. lock: In a multi-threaded environment, shutdown operations involve modifying critical state and performing operations that may affect multiple threads. The use of locks ensures that these operations are atomic and consistent, avoiding inconsistencies or surprises caused by simultaneous shutdown operations by multiple threads.
  2. Checking off permissions: State checking before shutdown ensures that the shutdown operation is legal and avoids shutting down at inappropriate times. Advancing state allows other parts of the code to react correctly based on the current state of the executor.
  3. Set the state to SHUTDOWN: Prevents new tasks from being submitted but completes existing tasks.
  4. Idle Thread Interruption
  5. Calling the onShutdown method (hook method)potential usePerform some specific cleanup or customization on shutdown, such as freeing up resourcesetc.
  6. release a lock
  7. Attempt to terminate the thread pool: The thread pool is actually terminated if all tasks have been completed.

The execution flow of the shutdown() method is shown below:

Post-lesson Reflections

Why do I need to close the thread pool? What are the scenarios for shutting down the thread pool? What is the flow of shutdownNow()?

This article has been included in my interview mini-site, which contains modules such as Redis, JVM, Concurrency, Concurrency, MySQL, Spring, Spring MVC, Spring Boot, Spring Cloud, MyBatis, Design Patterns, Message Queuing and more.