Java thread Pool Framework core code parsing _java

Source: Internet
Author: User
Tags throw exception

Objective
in multithreaded programming, assigning a thread to each task is unrealistic, and thread creation overhead and resource consumption are high. The thread pool came into being and became our tool for managing threads. Java, through the executor interface, provides a standard way to decouple a task's submission process from its execution and use runnable to represent a task.
Now, let's analyze the implementation threadpoolexecutor of the Java thread pool framework.
The following analysis is based on JDK1.7

Life cycle
Threadpoolexecutor
, the 3-bit height of capacity is used to represent the running state, respectively:
1.RUNNING: Receives new tasks and processes tasks in the task queue
2.SHUTDOWN: Do not receive new tasks, but tasks that process task queues
3.STOP: Do not receive new tasks, do not come out of the task queue, while interrupting all ongoing tasks
4.TIDYING: All tasks have been terminated and the number of worker threads is 0, which will execute terminated ()
5.terminated:terminated () execution completed


State transition Diagram

Threadpoolexecutor the state bit in atomic class
private final Atomicinteger ctl = new Atomicinteger (Ctlof (RUNNING, 0));

thread pool model
core parameters
 corepoolsize: The minimum number of surviving worker threads (if set allowcorethreadtimeout, then the value is 0)
 maximumpoolsize: Maximum number of threads, Limited to capacity
  keepalivetime: the duration of the corresponding thread, the time unit specified by Timeunit
 workqueue: Task Force column that stores pending tasks
  rejectexecutionhandler: Reject policy, the line Cheng triggers the maximum capacity of the
thread pool: The first three bits in capacity are used as a flag bit, that is, the maximum capacity of the worker thread is (2^29)-1
Four models
  Cachedthreadpool: A cacheable thread pool that, if the current size of the thread pool exceeds the processing requirements, reclaims idle threads and, when requirements increase, new threads can be added, and the size of the thread pool is not limited.
 fixedthreadpool: a fixed-size thread pool that creates a thread when a task is committed, until the maximum number of thread pools is reached, and the size of the thread pool will no longer change.
 singlethreadpool: A single-threaded thread pool that has only one worker thread to perform tasks, ensuring serial execution according to the order of tasks in the queue. If this thread ends unexpectedly, a new thread will be created to perform the task.
 scheduledthreadpool: a fixed size thread pool, and performs tasks in a deferred or timed manner, similar to a timer.

Execute task Execute
Core Logic:
1. Current thread count < Corepoolsize, open new core thread directly to execute task Addworker (command, True)
2. Current number of threads >= corepoolsize, and task join work queue succeeded

1). Check that the current state of the thread pool is in running
2). If no, the task is rejected
3. If yes, determine if the current number of threads is 0, and if 0, add a worker thread.
3. Open a normal thread to perform a task Addworker (command, false), turn off the task when it fails
From the above analysis, you can summarize the four stages of the thread pool operation:
1. Poolsize < corepoolsize and the queue is empty, a new thread is created to handle the committed task
2. Poolsize = = Corepoolsize, at which time the submitted task enters the work queue, and the worker thread obtains the task execution from the queue, when the queue is not empty and not full.
3). Poolsize = = Corepoolsize, and the queue is full, a new thread is also created to handle the submitted task, but Poolsize < maxpoolsize
4). Poolsize = = Maxpoolsize, and the queue is full, this will trigger a rejection policy

Reject Policy
We mentioned earlier that the task could not be executed and would be rejected, Rejectedexecutionhandler is the interface that handles the rejected task. Here are four rejection policies.
AbortPolicy: Default Policy, abort task, throw rejectedexception
Callerrunspolicy: performs the current task on the caller thread without throwing an exception
Discardpolicy: Discard the strategy, discard the task directly, do not throw the exception
Di Scardolderspolicy: Discard the oldest task, perform the current task, do not throw exception

Worker in the thread pool
The worker inherits Abstractqueuedsynchronizer and Runnable, which gives the worker the ability to lock, which executes the main method of the worker thread Runworker (worker W) (from the task queue). The Worker refers to the existence workers collection inside, uses Mainlock Guardian.
private final Reentrantlock mainlock = new Reentrantlock ();
Private final hashset<worker> workers = new hashset<worker> ();
core function Runworker
Here is the simplified logic, note: Each worker thread run performs the following function

 final void Runworker (Worker w) {
 Thread wt = Thread.CurrentThread ();
 Runnable task = W.firsttask;
 W.firsttask = null;
 while (Task!= null | | (Task = Gettask ())!= null) {
  w.lock ();
  BeforeExecute (WT, task);
  Task.run ();
  AfterExecute (task, thrown);
  W.unlock ();
 }
 Processworkerexit (w, completedabruptly);

1. Get the task from Gettask ()
2. Lock the Worker
3. Execute beforeexecute (WT, Task), which is an extension method that Threadpoolexecutor provides to subclasses
4. Run the task and if the worker has the first task configured, perform the first task and only once.
5. Implementation of AfterExecute (task, thrown);
6. Unlocking the Worker
7. If the obtained task is NULL, turn off the worker

Get Task Gettask
the task queue within the thread pool is a blocking queue that is passed in at construction time.
private final blockingqueue<runnable> workqueue;
Gettask () Gets the task from the task queue, supports blocking and timeout waiting tasks, and four causes the return of NULL to allow the worker to close.
1. The number of existing threads exceeds the maximum number of threads
2. Thread pool is in stop state
3. The thread pool is in shutdown state and the Task Force column is empty
4. The thread waits for the task to timeout, and the number of threads exceeds the number of reserved threads
Core logic: waiting for a task to timeout can cause the worker thread to shut down, depending on the timed on the blocking queue or blocking the wait task.

 Timed = Allowcorethreadtimeout | | WC > corepoolsize;
Runnable r = timed?
 Workqueue.poll (KeepAliveTime, timeunit.nanoseconds):
 workqueue.take (); 

Wait for a task to timeout in the following two situations:
1. Allow core threads to wait for timeout, i.e. allowcorethreadtimeout (true)
2. The current thread is a normal thread, at this time WC > corepoolsize
The work queue uses blockingqueue, where it is not expanded, and a detailed analysis is written later.

Summarize
Threadpoolexecutor based on the producer-consumer model, submitting tasks is equivalent to the producer, and the thread that executes the task is the consumer.
Executors provides four methods based on the Threadpoolexecutor constructed thread pool model, and in addition, we can directly inherit Threadpoolexecutor, Rewrite the BeforeExecute and AfterExecute methods to customize the thread pool task execution process.
Using a bounded or unbounded queue needs to be considered in terms of the size of the Task Force column and the number of threads.
Reject policies recommend the use of Callerrunspolicy, which does not discard tasks or throw exceptions, but instead returns the task to the caller thread for execution.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.