Java Concurrency: Implementation and principle of thread pool part 7 thread pool (2)

Source: Internet
Author: User

Thread Pool task execution process

We started from an API to learn how Executor processes task queues.

Java.util.concurrent.Executor.exe cute (Runnable)

Executes the given task sometime in the future. the task may execute in a new thread or in an existing pooled thread. if the task cannot be submitted for execution, either because this executor has been shutdown or because its capacity has been reached, the task is handled by the current RejectedExecutionHandler.

All tasks in the thread pool depend on this interface. This passage has the following meanings:

A task may be executed at a certain time in the future, but may not be executed immediately. Why are there two "Possibilities" here "? Continue to look below.
A task may be executed in a new thread or in a thread in the thread pool.
The task cannot be submitted for execution due to the following two reasons: the thread pool has been closed or the thread pool has reached the capacity limit.
All failed tasks will be processed by the "current" task rejection policy RejectedExecutionHandler.
Answer the above two "Possibilities". The task may be executed, which is not possible in case 3 described above; it may not be executed immediately because the task may still be queued in the queue, so it is still waiting for the allocation thread to execute. After understanding the literal problems, let's take a look at the specific implementation.

Public void execute (Runnable command ){
If (command = null)
Throw new NullPointerException ();
If (poolSize> = corePoolSize |! AddIfUnderCorePoolSize (command )){
If (runState = RUNNING & workQueue. offer (command )){
If (runState! = RUNNING | poolSize = 0)
EnsureQueuedTaskHandled (command );
}
Else if (! AddIfUnderMaximumPoolSize (command ))
Reject (command); // is shutdown or saturated
}
}
This piece of code looks simple. In fact, this is the most important part of the thread pool. If you can fully understand this part, the thread pool is quite easy. The entire execution process is as follows:

If the Task command is empty, a null pointer exception is thrown and a result is returned. Otherwise, perform 2.
If the current thread pool size is greater than or equal to the core thread pool size, perform 4. Otherwise, perform 3.
Create a new working Queue (thread, refer to the previous section). If it is successful, return directly. If it fails, perform step 4.
If the thread pool is running and the task is successfully added to the thread pool queue, perform Step 5. Otherwise, perform Step 7.
If the thread pool has been closed or the thread pool size is 0, perform 6. Otherwise, return directly.
If the thread pool is closed, a denial policy is executed. Otherwise, a new thread is started to execute the task.
If the thread pool size is not greater than the maximum number of thread pools, a new thread is started for execution. Otherwise, a denial policy is executed and the process ends.
Is the text description procedure simple enough? The following figure details the process.

To be honest, this figure is more difficult to understand than the above steps.

The process entry is very simple. We want to execute a task (Runnable command). Which of the following points does it end?

Based on the figure on the left, we know that there may be the following outlets:

(1) Based on the P1 and P7 in the figure, we can see that the task is only added to the task queue (offer (command;

(2) In Figure P3, this path does not add tasks to the task queue, but starts a new working thread (Worker) for Tail scanning. The user processes the empty task queue;

(3) P4 in the figure, this path does not add the task to the task queue, but a new Worker is started, and the first task at the job site is the current task;

(4) In the P5 and P6 in the figure, this path does not add the task to the task queue, nor start the working thread. It only throws the task rejection policy. P2 indicates that a task is added to the task queue, but the thread pool is closed. Therefore, it is deleted from the task queue and thrown to the denial policy.

If the above explanation is unclear, you can study the following two sections of code:

Java. util. concurrent. ThreadPoolExecutor. addIfUnderCorePoolSize (Runnable)
Java. util. concurrent. ThreadPoolExecutor. addIfUnderMaximumPoolSize (Runnable)
Java. util. concurrent. ThreadPoolExecutor. ensureQueuedTaskHandled (Runnable)
When will a task be executed immediately?

When the thread pool is running, if the thread pool size is smaller than the core thread pool size or the thread pool is full (the task queue is full) and the thread pool size is smaller than the maximum thread pool size (in this case, the thread pool size is greater than the core thread pool size). The program description is as follows:

RunState = RUNNING & (poolSize <corePoolSize | poolSize <maxnumPoolSize & workQueue. isFull ())
The preceding condition indicates that a task can be executed immediately.

With the foundation of execute, let's look at the implementation of several submit methods in ExecutorService.

Public Future <?> Submit (Runnable task ){
If (task = null) throw new NullPointerException ();
RunnableFuture <Object> ftask = newTaskFor (task, null );
Execute (ftask );
Return ftask;
}

Public <T> Future <T> submit (Runnable task, T result ){
If (task = null) throw new NullPointerException ();
RunnableFuture <T> ftask = newTaskFor (task, result );
Execute (ftask );
Return ftask;
}

Public <T> Future <T> submit (Callable <T> task ){
If (task = null) throw new NullPointerException ();
RunnableFuture <T> ftask = newTaskFor (task );
Execute (ftask );
Return ftask;
}
It's easy, isn't it? The execution process of the execute method is complicated for a thread pool. In the next section, we will discuss how to obtain the task execution result, that is, the use and principle of the Future class.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.