Java thread pool

Source: Internet
Author: User

1. Threadpoolexecutor logical structure and mode of operation

When we created the thread pool, we used one of the simplest constructors in Threadpoolexecutor:

public ThreadPoolExecutor(int corePoolSize,                              int maximumPoolSize,                              long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue)

Parameters that need to be passed into the constructor include Corepoolsize, Maximumpoolsize, KeepAliveTime, Timeunit, and Workqueue. To clearly understand the meaning of these parameters (and the parameters that will be introduced later), it is first to clarify the logical structure of the threadpoolexecutor thread pool.

It is important to note the concept that the container that exists in the thread pool must be a thread object, not a task that you require to run (so it is called a thread pool, not a task pool, not a pool of objects, let alone a pool) The task you require to run is run by a thread pool that is assigned to a free thread.

From there, we can see several important elements that make up the thread pool:

    • Wait queue: As the name implies, you call the Submit () method or the Execute () method of the thread pool object, which requires the tasks that the thread pool runs (these tasks must implement the Runnable interface or the callable interface). But for some reason the thread pool does not run these tasks immediately, but instead feeds into a queue for execution (these reasons are explained shortly).

    • Core thread: The thread pool is primarily used to perform tasks that are "core threads", and the number of "core threads" is determined by the Corepoolsize parameter that you set when you created the thread. If no special setting is made, the number of threads in the thread pool will always remain corepoolsize (excluding the creation phase).

    • Non-core thread: Once the number of tasks is too large (determined by the nature of the wait queue), the thread pool creates a "non-core thread" temporary help run task. The portion you set that is larger than the Corepoolsize parameter is less than the maximumpoolsize parameter, which is the maximum number of "non-core threads" that the thread pool can temporarily create. in this case, if a thread is not running any tasks, after waiting for the KeepAliveTime time, the thread will be destroyed until the thread pool's number of threads has reached Corepoolsize again.

    • To focus on the contents of the boldface section of the previous description. In other words, not so-called "non-core threads" will be recycled, but who's free time to reach KeepAliveTime this threshold, will be recycled. Until the number of threads in the thread pool equals corepoolsize. The

    • Maximumpoolsize parameter is also the maximum number of threads allowed to be created by the current thread pool. Then, if you set the Corepoolsize parameter to match the Maximumpoolsize parameter you set, the thread pool will not reclaim idle threads under any circumstances. KeepAliveTime and Timeunit also lost their meaning. The

    • KeepAliveTime parameter and the Timeunit parameter are also used together. The KeepAliveTime parameter indicates the quantization value of the wait time, Timeunit indicates the unit of quantization value. For example, Keepalivetime=1,timeunit is timeunit.minutes and the recycle threshold value for idle threads is 1 minutes.

Having said the logical structure of the thread pool, let's talk about how the thread pool handles one of the running tasks. Describes a complete task-handling process:

1. First, you can require the thread pool to perform a task by using the Submit () method or the Execute () method provided by the thread pooling. After the thread pool receives this request to perform the task, there are several processing situations:

1.1. If the number of threads running in the current thread pool has not reached the corepoolsize size, the line pool creates a new thread to run your task, regardless of whether the previously created thread is idle .

1.2. If the number of threads running in the current thread pool has reached the corepoolsize size set, the thread pool will add your task to the wait queue. Until one of the threads is idle, the thread pool takes a new task execution from the queue based on the waiting queue rule you set.

1.3, If according to the queue rules, this task cannot join the waiting queue. The thread pool will then create a "non-core thread" to run this task directly . Note that if the task executes successfully in this case, then the number of threads in the front-thread pool must be greater than corepoolsize.

1.4. If this task cannot be executed directly by the "core thread", cannot join the wait queue, and cannot create a "non-core thread" to execute directly, and you do not set Rejectedexecutionhandler for the thread pool. The thread pool throws a Rejectedexecutionexception exception, which is where the thread pool refuses to accept the task. ( actually throwing the rejectedexecutionexception exception is a default Rejectedexecutionhandler implementation in the Threadpoolexecutor thread pool: AbortPolicy, This will be mentioned later in this article )

2. Once a thread in a thread pool completes the execution of a task, it tries to get to the task waiting queue for the next waiting task (all the wait tasks implement the Blockingqueue interface, which, by the interface literal understanding, is a blocking queue interface), which invokes the poll waiting queue ( ) method, and stay where.

3. When threads in the thread pool exceed the Corepoolsize parameter that you set, there is a so-called "non-core thread" in the current thread pool. Then, when a thread finishes working on a task, it will be recycled if there is still no new task assigned to it after waiting for keepalivetime time. When the thread pool recycles threads, it is not equal to the so-called "core threads" and "non-core threads" until the recycle process stops until the number of threads in the thread pools equals the corepoolsize parameter that you set.

4, Java provides four kinds of thread pool through executors, respectively:

    • Newcachedthreadpool creates a cacheable thread pool that can flexibly reclaim idle threads if the thread pool length exceeds the processing needs, and creates a new thread if it is not recyclable.
    • Newfixedthreadpool creates a thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue.
    • Newscheduledthreadpool creates a fixed-line pool that supports timed and recurring task execution.
    • Newsinglethreadexecutor creates a single threaded thread pool that performs tasks with only a single worker thread, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority).


Java thread pool

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.