Java Concurrency Programming Summary 5--threadpoolexecutor

Source: Internet
Author: User

I. Introduction of Threadpoolexecutor

In jdk1.8, there are 4 constructor functions. To

Threadpoolexecutor (int corepoolsize, int maximumpoolsize, long keepalivetime, timeunit unit, blockingqueue<runnable > WorkQueue, threadfactory threadfactory, Rejectedexecutionhandler handler) for example:

1.corepoolsize: Core thread pool Size

2.maximumpoolsize: Maximum thread pool size

3.KeepAliveTime: When the number of threads in the thread pool is greater than corepoolsize, the extra idle thread waits for the maximum time of the new task, and the extra thread terminates after that time

4,Unit: Time units, such as milliseconds, nanoseconds, etc.

5.workQueue: Blocking queue

6,threadfactory: Create thread factory, can easily create threads, can be customized; Default is Executors.defaultthreadfactory

7,handler: Saturation policy, default is AbortPolicy

Defining a complete thread pool can be written like this:

Private Threadpoolexecutor Defaultthreadpool = new Threadpoolexecutor (ten, +, Timeunit.milliseconds, new Linkedblockingqueue<runnable> (+), Executors.defaultthreadfactory (), New Threadpoolexecutor.discardpolicy ());

The main processing flow for the thread pool is as follows:

1. Submit the task to the thread pool to determine if the core thread pool (corepoolsize) is full? Not full, create a worker thread to perform the task; full, go to the next process.

2. The thread pool determines if the work queue (WorkQueue) is full? is not full, the newly submitted task is stored in the work queue. Full, then go to the next process.

3. Determine if the entire thread pool (maximumpoolsize) is full? is not full, a new worker thread is created to perform the task, and the Saturation policy (Rejectedexecutionhandler) is assigned to handle the task.

Second, saturation strategy Rejectedexecutionhandler

4 types of Rejectedexecutionhandler are defined in the Threadpoolexecutor class:

1,abortpolicy: Default policy, directly throws Rejectedexecutionexception exception.

2.callerrunspolicy: Only use the caller's thread to run the task.

3.Discardoldestpolicy: Discards the most recent task in the queue and executes the current task.

4,discardpolicy: Do not handle, discard.

You can also customize the saturation strategy, such as adding a new task that cannot be processed to the log, just implement the Rejectedexecutionhandler interface.

Third, blocking queue Blockingqueue

 /**  * Arrayblockingqueue: bounded block queue consisting of array structure, queue follows FIFO  * /     PrivateBlockingqueue<string> ABQ =NewArrayblockingqueue<string> (10);  /**  * Linkedblockingqueue: A blocking queue consisting of a list structure, FIFO * Linkedblockingdeque: A two-way blocking queue consisting of a list structure, a construction method, and a linkedb Lockingqueue similar to * public linkedblockingqueue (int capacity)//bounded blocking queue with a queue maximum of capacity * public linkedblockingqueue () {This (integer.max_value);} Unbounded blocking queue, with a queue maximum of Integer.max_value * The thread pool created by executors.newfixedthreadpool (int nthreads) is bounded by unbounded linkedblockingqueue * For put and take operations, different locks are used internally: Putlock, Takelock, and arrayblockingqueue internal only one lock  *  /    PrivateBlockingqueue<thread> LBQ =NewLinkedblockingqueue<thread> (10); PrivateExecutorservice Fixedthreadpool = Executors.newfixedthreadpool (10); Privateblockingqueue<string> LBD =NewLinkedblockingdeque<string>();  /**  * priorityblockingqueue: Bounded blocking queue that supports priority ordering * Public priorityblockingqueue (int initialcapacity, C omparator<? Super E> Comparator)  *  /    Privateblockingqueue<string> PBQ =NewPriorityblockingqueue (100,NewComparator<string>() {         Public intCompare (String O1, String O2) {returnO1.compareto (O2);//Ascending order        }    });  /**  * Delayqueue: An unbounded blocking queue implemented using priority queue, which supports the delay acquisition element and is suitable for the design of the cache system and scheduling of scheduled tasks. * Internal queue using Priorityqueue, private final priorityqueue<e> q = new priorityqueue<e> (); * Queue elements need to implement Delayed interface, class Delayqueue<e extends delayed> extends abstractqueue<e> *//**< /c4> * Synchronousqueue: Blocking queue that does not store elements  *//**  * linkedtransferqueue: A linked list structure implements the TRA Unbounded blocking queue for Nsferqueue interface * Transfer method: If the current consumer is waiting for the receive element (take () or poll (long timeout, Timeunit unit) method, the producer's incoming element can be passed directly to the consumer without Into the queue  * / Blockingqueue<String> LTQ =NewLinkedtransferqueue<string> ();

Iv. creating a thread pool through executors

 /**  * Create a single thread for scenarios that require guaranteed sequential execution of tasks * return new Finalizabledelegatedexecutorservice (new Threa Dpoolexecutor (1, 1, 0L, Timeunit.milliseconds, New Linkedblockingqueue<runnable> ())); * Blockingqueue uses unbounded linkedblockingqueue, so maximumpoolsize, keepalivetime parameters are meaningless * / Executors.newsinglethreadexecutor ();
/** * Create a fixed thread for servers that need to limit the current number of threads, load the heavier server * return new Threadpoolexecutor (Nthreads, Nthreads , 0L, Timeunit.milliseconds, New linkedblockingqueue<runnable> ()); * Use unbounded linkedblockingqueue, so maximumpoolsize, keepalivetime parameters meaningless * /Executors.newfixedthreadpool (10);
/** * Create threads as needed, for small programs that perform many short-term asynchronous tasks, or for servers with lighter load * return new Threadpoolexecutor (0, Integer . Max_value, 60L, Timeunit.seconds, New synchronousqueue<runnable> ()); * The initial thread is 0, with Synchronousqueue blocking queue, if the production task speed is lower than the speed of consumption, idle 60s thread will be terminated; If the production task continues to be faster than the consumption rate, a new thread is created continuously * /Executors.newcachedthreadpool ();
/** * Run tasks after a given delay, or perform tasks on a regular basis * super (corepoolsize, Integer.max_value, 0, nanoseconds, new Delayedworkqueue ()); * Use unbounded delayqueue queue, so maximumpoolsize, keepalivetime parameters meaningless * /Executors.newscheduledthreadpool (10);

Java Concurrency Programming Summary 5--threadpoolexecutor

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.