Java Thread Pool Threadpoolexecutor understanding

Source: Internet
Author: User

Java provides four thread pools through executors, namely:
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).

Be familiar with these four kinds of thread pool, first understand Threadpoolexecutor

The following properties are important to define in Threadpoolexecutor

Corepoolsize: The number of threads in the thread pool, which is enabled by default on several threads in the thread pool to process tasks in the task queue

(Note: This is not fixed and varies depending on the implementation type of the queue (WorkQueue))

Maximumpoolsize: The maximum number of threads in the thread pool, this attribute feels the corepoolsize conflict with the above, clearly defines the thread data above, how to control the

The maximum number of threads is, in fact, the same as mentioned above (depending on the implementation type of the queue (WorkQueue), this property needs to be used for the corresponding task rejection policy)

keepalivetime;//more than corepoolsize idle threads, and how long they will be destroyed
Units of the Timeunit Unit;//keepalivetime
Blockingqueue<runnable> workQueue: Task queue, Task submitted but not yet executed

There are several types of implementations:

Synchronousqueue: The queue that is submitted directly, the queue does not have capacity, each wipe operation should correspond to a corresponding delete operation, whereas each delete operation corresponds to the corresponding insert operation.

Synchronousqueue does not save the task, it always carries the task to the thread execution, if there is no idle process, then attempts to create a new process if the process

The maximum number of threads set by the Maximumpoolsize has been reached, the deny policy is enforced

Arrayblockingqueue: Bounded task queue, the Arrayblockingqueue constructor must take a capacity parameter (for example, N) to indicate the maximum capacity of the queue.

When a new task executes, this defines the current number of threads as T, the capacity parameter of the constructor is N, and the current queue length is L

1.t<corepoolsize, create a new thread heart

2.t>corepoolsize and L<n when inserted into the task queue, waiting for the idle thread to execute

3.t>corepoolsize and L>=n, create a new thread to perform a new task

4.t>maximumpoolsize, the Deny policy is enforced.

Linkedblockingqueue: Unbounded task queue, when a new task is executed, creates a new thread if the thread pool has fewer threads than corepoolsize, otherwise enters the queue waiting.

           Without task creation speed and processing speed differences, unbounded queues will continue to grow rapidly until the system memory is exhausted

Priorityblockingqueue: Priority queue, which controls the order in which tasks are executed, is a special unbounded queue. Regardless of bounded queue unbounded queue, are based on FIFO algorithm

Processing tasks (verbose), which can be performed sequentially according to the priority order of the task itself.

Threadfactory threadfactory//thread Factory, used to create threads, general default
Rejectedexecutionhandler handler;//rejection policy, how to reject a task when too many tasks are too late to process

The following rejection policies are built into the JDK:

Abortpolity policy: This policy throws an exception directly, preventing the system from working properly

Callerrunspolity policy: As long as the thread is closed, the policy runs the currently discarded task directly in the caller thread

Discardoledstpolicy policy: This policy discards the oldest request, a task that is about to be executed, and attempts to commit the current task again.

Discardplicy policy: This policy silently discards the tasks that cannot be handled and does not handle tasks.

If the above policies do not meet the actual application requirements, you can extend the Rejectedexecutionhandler interface

 Public Interface Rejectedexecutionhandler {    void  rejectedexecution (Runnable R, Threadpoolexecutor executor );}

where r is the task that the request executes, executor is the current thread pool.

Understanding the above attributes of Threadpoolexecutor, and then analyzing the executors to provide four thread pools is simple.

Executors.newfixedthreadpool (Nthreads)

     Public Static Executorservice newfixedthreadpool (int  nthreads) {        returnnew  Threadpoolexecutor (Nthreads, nthreads,                                      0L, timeunit.milliseconds,                                      new Linkedblockingqueue<runnable>());    }

Returns a corepoolsize, maximumpoolsize the thread pool of equal size and uses the Linkedblockingqueue task queue, because there is no dynamic number of threads for a fixed-size thread pool

Change, so corepoolsize, and maximumpoolsize can be equal, while it uses unbounded queues to hold tasks that cannot be performed immediately, and when the task is committed very frequently, the queue may swell rapidly, thus exhausting

system resources.

Executors.newsinglethreadexecutor ()

     Public Static Executorservice Newsinglethreadexecutor () {        returnnew  Finalizabledelegatedexecutorservice            (new threadpoolexecutor (1, 1,                                    0L, Timeunit.milliseconds,                                    new linkedblockingqueue<runnable>()));    }

A thread pool that returns a single thread is a degenerate of the Newfixedthreadpool () method, simply setting the thread pool's number of threads to 1

Executors.newcachedthreadpool ()

 Public Static Executorservice Newcachedthreadpool () {        returnnew threadpoolexecutor (0, Integer.max_value,                                      60L, timeunit.seconds,                                      new synchronousqueue<runnable> ());    }

Returns a thread pool of corepoolsize of 0 maximumpoolsize Infinity, which means that in the absence of a task, the thread is within a wireless path, and when the task is committed, the thread pool uses the idle thread to perform the task, without idle

Thread, the task is joined to the Synchronousqueue queue, and the Synchronousqueue queue is a directly committed queue that always forces the thread pool to add new threads to perform the task, and when the task finishes executing,

Because Corepoolsize is 0, empty threads are recycled for a specified period of time (60s).

For Newcachedthreadpool (), if a large number of tasks are committed at the same time, and the task is executed less quickly, then the system will turn on the same amount of threading, which may quickly deplete the system's resources.

Java Thread Pool Threadpoolexecutor understanding

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.