This is the seventh day of my participation in the August More text Challenge. For details, see:August is more challenging

About the author: Wu Kong, 8 years of experience in first-line Internet development and architecture, explains distribution, architecture design, Java core technology with stories. “JVM performance optimization combat” column author, open source “Spring Cloud combat PassJava” project, public number: Wukong chat architecture. This article is available at www.passjava.cn

The lifetime of the thread pool

The thread pool life cycle includes:

  • RUNNING: Receives new tasks and processes tasks in the queue
  • SHUTDOWN: No new tasks are accepted, but queued tasks are processed
  • STOP: Does not receive new tasks, does not process tasks in the queue, and interrupts tasks in processing
  • TIDYING: All task processing is complete and the valid thread count is 0
  • TERMINATED: The TERMINATED () method is finished.

Lifecycle states correspond to methods:

Denial policy of the thread pool

If all threads in the thread pool are busy and the work queue is full (provided that the work queue is bounded), then the task is submitted and the thread pool rejects it. As for the rejection policy, you can specify it with the handler parameter.

ThreadPoolExecutor already provides the following four policies.

  • CallerRunsPolicy: The submitting thread executes the task itself.
  • AbortPolicy: will the default refusal strategies, throws RejectedExecutionException.
  • DiscardPolicy: Directly discards the task without throwing any exceptions.
  • DiscardOldestPolicy: Discarding the oldest task. This policy is to discard the oldest task and add the new task to the work queue.

The RejectedExecutionHandler interface is implemented by the above built-in rejection policies. If the above policies do not meet the actual needs, you can extend RejectedExecutionHandler interface.