banner
RustyNail

RustyNail

coder. 【blog】https://rustynail.me 【nostr】wss://ts.relays.world/ wss://relays.world/nostr

ThreadPoolExecutor

ThreadPoolExecutor is a service (ExecutorService) used to execute submitted tasks. Typically, tasks are placed in threads from the thread pool for execution.

ThreadPoolExecutor can have different types of thread pools. This can be achieved through different creation methods: Executors.new****ThreadPool()

  • newCachedThreadPool has no boundaries and creates a new thread every time.
  • newFixedThreadPool has a fixed thread size.
  • newSingleThreadExecutor is a single-threaded thread pool.

core / maximum pool size#

When a new task is submitted (execute(runnable)), the destination of the task is determined based on the settings of the MaximumPoolSize and CorePoolSize parameters.

If the current number of running threads is greater than CorePoolSize and less than MaximumPoolSize, and the current waiting queue is full, a new thread will be created.

In other words, if these two parameters are set to the same value, it is equivalent to creating a FixedThreadPool. And if MaximumPoolSize is set to a large value, it is equivalent to creating a CachedThreadPool.

Keep-alive times#

The thread's lifespan is the time it takes for the thread to be released when it is not working. If set to a large number, it takes a long time to reclaim resources. It cannot be zero.

Rejection policies#

If the core pool size, maximum pool size, and queue are all full, the newly added task needs to be handled. There are several ways to handle this:

  1. Execute the task directly in the execute() thread.
  2. Throw a RejectedExecutionException exception.
  3. Discard the task.
  4. Discard the oldest (head of the queue) thread.

These are the provided options, but you can also implement the RejectedExecutionHandler interface yourself.

new RejectedExecutionHandler() {
    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

    }
}

State transitions#

Throughout its lifecycle, it transitions between Running, Stop, Shutdown, Tiddying, and Terminated states.

State Machine

Inner class#

worker#

Used to execute tasks. The Service's private boolean addWorker(Runnable firstTask, boolean core) method creates and executes workers based on the state.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.