Java concurrent programming Summary 5 -- ThreadPoolExecutor, java concurrent programming practices

Source: Internet
Author: User

Java concurrent programming Summary 5 -- ThreadPoolExecutor, java concurrent programming practices

I. Introduction to ThreadPoolExecutor

In jdk1.8, there are four constructors. To

ThreadPoolExecutor (int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue <Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler:

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 the corePoolSize, the maximum time for the redundant Idle threads to wait for the new task is longer than this time. After this time, the redundant threads terminate.

4,Unit: Time unit, such as millisecond and nanoseconds

5,WorkQueue: Blocking queue

6,ThreadFactory: Create a thread factory. You can easily create and customize threads. The default value is Executors. DefaultThreadFactory.

7,Handler: Saturation policy. The default value is AbortPolicy.

 

You can define a complete thread pool as follows:

Private ThreadPoolExecutor defathreadpool = new ThreadPoolExecutor (10,100,100, TimeUnit. MILLISECONDS, new LinkedBlockingQueue <Runnable> (1000), Executors. defaultThreadFactory (), new ThreadPoolExecutor. DiscardPolicy ());

 

The main processing process of the thread pool is as follows:

1. Submit the task to the thread pool to check whether the Core Thread Pool (corePoolSize) is full? If it is not full, create a working thread to execute the task. If it is full, enter the next process.

2. Does the thread pool determine whether the workQueue is full? If it is not full, the newly submitted tasks are stored in the Task Force column. If it is full, the next process is started.

3. Check whether the entire thread pool (maximumPoolSize) is full? If it is not full, a new working thread is created to execute the task. If it is full, it is handed over to the saturation Policy (RejectedExecutionHandler) to process the task.

 

Ii. saturation policy RejectedExecutionHandler

Four RejectedExecutionHandler types are defined in the ThreadPoolExecutor class:

1,AbortPolicy: The Default policy directly throws a RejectedExecutionException.

2,CallerRunsPolicy: Run the task only in the thread where the caller is located.

3,DiscardOldestPolicy: Discard the most recent task in the queue and execute the current task.

4,DiscardPolicy: Do not process, discard.

You can also customize the saturation policy, such as adding new tasks that cannot be processed to logs. You only need to implement the RejectedExecutionHandler interface.

 

3. BlockingQueue

/*** ArrayBlockingQueue: A Bounded blocking queue consisting of arrays. Queues follow FIFO */Private BlockingQueue <String> abq = new ArrayBlockingQueue <String> (10 );/*** Blocked blockingqueue: a blocking queue composed of linked lists. FIFO * blocked blockingdeque: a bidirectional blocking queue consisting of linked lists. The constructor is similar to * public blocked blockingqueue (int capacity) // bounded blocking queue. The maximum queue value is capacity * public blocked blockingqueue () {this (Integer. MAX_VALUE);} // the unbounded blocking queue. the maximum value of the queue is Integer. MAX_VALUE * through Executors. the thread pool created by newFixedThreadPool (int nThreads) adopts the unbounded writable blockingqueue * For put and take operations, different internal locks are used: putLock, takeLock, and ArrayBlockingQueue has only one internal lock */Private BlockingQueue <Thread> lbq = new LinkedBlockingQueue <Thread> (10); private ExecutorService fixedThreadPool = Executors. newFixedThreadPool (10); private BlockingQueue <String> lbd = new LinkedBlockingDeque <String> ();/*** PriorityBlockingQueue: A Bounded blocking queue that supports priority sorting * public PriorityBlockingQueue (int initialCapacity, Comparator <? Super E> comparator )*/Private BlockingQueue <String> pbq = new PriorityBlockingQueue (100, new Comparator <String> () {public int compare (String o1, String o2) {return o1.compareTo (o2 ); // sort in ascending order }});/*** DelayQueue: an unbounded blocking queue implemented by the priority queue. It supports Time-delay elements and is suitable for Cache System Design and scheduled task scheduling. * Internal queues use PriorityQueue and private final PriorityQueue <E> q = new PriorityQueue <E> (); * The queue element must implement the Delayed interface, class DelayQueue <E extends Delayed> extends AbstractQueue <E> * // *** SynchronousQueue: block queue without storing elements * // *** cancel transferqueue: the TransferQueue interface's unbounded blocking queue * transfer method is composed of linked list structures. If the current consumer is waiting for the receiving element (take () or poll (long timeout, TimeUnit unit) method, the elements imported by the producer can be directly transmitted to the consumer without being put into the queue */BlockingQueue <String> ltq = new encrypted transferqueue <String> ();

 

4. Create a thread pool through Executors

/*** Create a single thread, which is suitable for scenarios where tasks need to be executed sequentially * return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor (1, 1, 0L, TimeUnit. MILLISECONDS, new LinkedBlockingQueue <Runnable> (); * BlockingQueue uses unbounded LinkedBlockingQueue, so the maximumPoolSize and keepAliveTime parameters are meaningless */Executors. newSingleThreadExecutor ();
/*** Create a fixed thread. It is suitable for servers with heavy loads that need to limit the number of current threads. * return new ThreadPoolExecutor (nThreads, nThreads, 0L, TimeUnit. MILLISECONDS, new LinkedBlockingQueue <Runnable> (); * use unbounded LinkedBlockingQueue, so the maximumPoolSize and keepAliveTime parameters are meaningless */Executors. newFixedThreadPool (10 );
/*** Create a thread as needed, suitable for small programs that execute many short-term asynchronous tasks, or servers with lighter loads * return new ThreadPoolExecutor (0, Integer. MAX_VALUE, 60L, TimeUnit. SECONDS, new SynchronousQueue <Runnable> (); * The initial thread is 0 and SynchronousQueue is used to block the queue. If the production task speed is lower than the consumption speed, 60 s of Idle threads will be terminated; if the production task speed is higher than the consumption speed, a new thread will be created continuously */Executors. newCachedThreadPool ();
/*** Run the task after the specified delay, or regularly execute the task * super (corePoolSize, Integer. MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue (); * use unbounded DelayQueue queues, so the maximumPoolSize and keepAliveTime parameters are meaningless */Executors. newScheduledThreadPool (10 );

 

 

 

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.