Introduction of "Turn" thread pool system and the correct creation method of learning thread pool from Ali Java Development Manual

Source: Internet
Author: User

Introduction of Java.util.concurrent.Executor thread pool system in jdk1.7

Java.util.concurrent.Executor: The root interface responsible for thread usage and scheduling
|–executorservice:executor sub-interface, the main interface of the thread pool
Implementation class of |–threadpoolexecutor:executorservice
|–scheduledexecutorservice:executorservice Sub-interface, responsible for thread scheduling
|–scheduledthreadpoolexecutor: Both inherited the Threadpoolexecutor and realized the Scheduledexecutorservice

In the actual use of the process, we do not need to manually new thread pool, Juc tool class executors provides us with a method to create a thread pool: ( Note: Recently Ali published Java Development Manual to force the thread pool is not allowed to use executors to create, but through Threadpoolexecutor way, such a way to let the students write more clearly the thread pool running rules, to avoid the risk of resource exhaustion. The following reprint part has the more detailed introduction )

executorservice newfixedthreadpool (): Create a fixed-size thread pool
executorservice Newcachedthreadpool (): Cache thread pool, the number of thread pools is not fixed, you can change the quantity automatically based on demand.
executorservice newsinglethreadexecutor (): Creates a single thread pool. There is only one thread in the thread pool

scheduledexecutorservice Newscheduledthreadpool (): Creates a fixed-size thread pool that can be deferred or timed to perform tasks.

Reprint part:Objective

Look at Ali's Java Development Manual recently, a recommendation from the thread pool above:

The "force" thread pool is not allowed to use executors to create, but by Threadpoolexecutor Way,
This way of processing let the students write more clearly the thread pool running rules, to avoid the risk of resource exhaustion.

In conjunction with the recent interview experience, it is useful to find this advice because you often use the factory method provided by executors to create a thread pool, ignoring the implementation within the thread pool.
In particular, the rejection strategy, the interview was asked two times, because using executors to create a thread pool will not pass this parameter and use the default value so we often ignore this parameter, fortunately, because of this advice, I am familiar with the threadpoolexecutor in advance.

Threadpoolexecutor

First look at how to create a thread pool using Threadpoolexecutor:

     Public threadpoolexecutor( intCorepoolsize,intMaximumpoolsize,Long KeepAliveTime, timeunit unit, blockingqueue<runnable > WorkQueue, threadfactory threadfactory, Rejectedexecutionha Ndler handler) 

Corepoolsize-the size of the thread pool core pool.
Maximumpoolsize-The maximum number of threads for the thread pool.
KeepAliveTime-When the number of threads is greater than the core, this is the maximum time to wait for a new task before terminating the extra idle thread.
The time unit of the unit-keepalivetime.
WorkQueue-Used to store queues waiting to perform tasks.
Threadfactory-Thread factory.
Handler-Deny policy.

Focus point 1 thread pool size

The thread pool has two thread-count settings, one for the core pool thread and one for the maximum number of threads.
After the thread pool has been created, by default, there are no threads in the thread pools until a task is created to perform the task, unless the prestartallcorethreads () or Prestartcorethread () method is called
When the number of threads created equals Corepoolsize, the set blocking queue is added. When the queue is full, thread execution tasks are created until the number in the thread pool equals maximumpoolsize.

Focus on point 2 appropriate blocking queue

Java.lang.IllegalStateException:Queue full
The method throws an exception to return a special value that always blocks timeout exits
Insert method Add (E) offer (e) put (e) offer (E,time,unit)
Removal method Remove () poll () Take () poll (Time,unit)
Check method Element () Peek () is not available

Arrayblockingqueue: A bounded blocking queue consisting of an array structure.
Linkedblockingqueue: A bounded blocking queue consisting of a list structure.
Priorityblockingqueue: A unbounded blocking queue that supports priority ordering.
Delayqueue: An unbounded blocking queue implemented with a priority queue.
Synchronousqueue: A blocking queue that does not store elements.
LinkedTransferQueue: An unbounded blocking queue consisting of a linked list structure.
Linkedblockingdeque: A two-way blocking queue consisting of a linked list structure.

Focus on point 3 explicit rejection policy

Threadpoolexecutor.abortpolicy: Discards the task and throws a rejectedexecutionexception exception. Default
Threadpoolexecutor.discardpolicy: Also discards the task, but does not throw an exception.
Threadpoolexecutor.discardoldestpolicy: Discards the first task in the queue and then tries to perform the task again (repeat this process)
Threadpoolexecutor.callerrunspolicy: The task is handled by the calling thread

Description: Executors The disadvantages of each method:
1) Newfixedthreadpool and Newsinglethreadexecutor:
The main problem is that the backlog of request processing queues can consume very large memory, even OOM.
2) Newcachedthreadpool and Newscheduledthreadpool:
The main problem is that the maximum number of threads is integer.max_value, which can create a very large number of threads, even OOM.

Executors

Let's look at the few factory methods provided by executors.

Newsinglethreadexecutor

Creates a single threaded pool of threads. This thread pool has only one thread at work, which is equivalent to single-threaded serial execution of all tasks. If this unique thread ends because of an exception, a new thread will replace it.
This thread pool guarantees that the order in which all tasks are executed is performed in the order in which the tasks are submitted.

New Threadpoolexecutor (1, 1,0l,timeunit.milliseconds,new linkedblockingqueue<runnable> ());
Newfixedthreadpool

Creates a fixed-size thread pool. Each time a task is committed, a thread is created until the thread reaches the maximum size of the threads pool.
Once the maximum size of the thread pool is reached, the thread pool will be replenished with a new thread if it ends up executing an exception.

New New Linkedblockingqueue<runnable> ());
Newcachedthreadpool

Creates a cacheable pool of threads. If the size of the thread pool exceeds the thread that is required to process the task,
Then a partially idle (60 second non-performing) thread is reclaimed, and when the number of tasks increases, the thread pool can intelligently add new threads to handle the task.
This thread pool does not limit the size of the thread pool, and the thread pool size is entirely dependent on the maximum thread size that the operating system (or JVM) can create.

New Threadpoolexecutor (0, Integer.max_value, 60L, Timeunit.seconds,new synchronousqueue<runnable> ());

Reprinted from: http://www.cnblogs.com/javanoob/p/threadpool.html

Introduction of "Turn" thread pool system and the correct creation method of learning thread pool from Ali Java Development Manual

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.