Threadpoolexecutor for Java concurrent programming

Source: Internet
Author: User

Package java. util. Concurrent .*
[1]. common thread pools 

The most common construction method is:

Threadpoolexecutor (INT corepoolsize,
Int maximumpoolsize,
Long KeepAliveTime,
Timeunit unit,
Blockingqueue <runnable> workqueue,

Threadfactory,

Rejectedexecutionhandler handler)

 

The configured thread pool that comes with JDK:

// Fixed the number of worker threads in the thread pool
Executorservice executorservice1 = executors. newfixedthreadpool (3 );

// A cacheable Thread Pool
Executorservice executorservice2 = executors. newcachedthreadpool ();

// Single-threaded executor
Executorservice executorservice3 = executors. newsinglethreadexecutor ();

// Supports scheduled and periodic task execution
Executorservice executorservice4 = executors. newscheduledthreadpool (3 );
These predefined thread pool services are also configured based on threadpoolexecutor, so we should start with the basic parameters., As follows:

Parameter description:
[1],Corepoolsize: Minimum number of thread pool maintenance threads
[2],Maximumpoolsize: Maximum number of thread pool maintenance threads
[3],KeepAliveTime: The idle time allowed by the thread pool maintenance thread
[4],Unit: The unit of idle time allowed by the thread pool maintenance thread. The optional parameter of unit is several static attributes in Java. util. Concurrent. timeunit:

    • Nanoseconds
    • Microseconds
    • Milliseconds
    • Seconds

[5],Workqueue: Buffer Queue used by the thread pool, which is commonly used: Java. util. Concurrent. arrayblockingqueue

[6]Threadfactory is responsible for creating a thread factory for the thread pool.The threads in the thread pool are created by threadfactory. If this parameter is not specified, executors. defaultthreadfactory is used to create a non-daemon thread with the same thread group and the same priority (norm_priority. If you specify threadfactory, you can customize attributes such as thread name, thread group, priority, and whether it is a daemon thread.
[7],Handler: The thread pool has four options for processing a denial task:

    • Threadpoolexecutor. abortpolicy (): throw a java. util. Concurrent. rejectedexecutionexception.
    • Threadpoolexecutor. callerrunspolicy (): retries to add the current task. It will automatically repeat the execute () method
    • Threadpoolexecutor. discardoldestpolicy (): discard the old task
    • Threadpoolexecutor. discardpolicy (): discard the current task

[2]. Detailed Description 
[1] when a task is added to the thread pool through the execute (runnable) method: 

      • If the number of threads in the thread pool is smaller than corepoolsize, a new thread should be created to process the added tasks even if all threads in the thread pool are idle.
      • If the number in the thread pool is equal to corepoolsize, but the Buffer Queue workqueue is not full, the task is put into the buffer queue.
      • If the number in the thread pool is greater than corepoolsize, the Buffer Queue workqueue is full, and the number in the thread pool is smaller than maximumpoolsize, a new thread is created to process the added task.
      • If the number in the thread pool is greater than corepoolsize, the Buffer Queue workqueue is full, and the number in the thread pool is equal to maximumpoolsize, the handler policy is used to process the task. That is, the processing task priority is: Core Thread corepoolsize, task queue workqueue, maximumpoolsize. If all three are full, handler is used to process the rejected task.
      • When the number of threads in the thread pool is greater than corepoolsize, if the idle time of a thread exceeds KeepAliveTime, the thread will be terminated. In this way, the thread pool can dynamically adjust the number of threads in the pool.

 

Threadpoolexecutor working mechanism:

 

The entire threadpoolexecutor task can be processed in four steps:

 

    • Step 1: The initial poolsize <corepoolsize, the submitted runnable task, will be directly used as the parameter of a new thread and immediately executed
    • Step 2: when the number of submitted tasks exceeds the corepoolsize, proceed to step 2. The current runable will be submitted to a block queue.
    • Step 3: If the block queue is a bounded queue, it enters step 3 when the queue is full. If poolsize <maximumpoolsize, a new thread will be tried for emergency handling and the corresponding runnable task will be executed immediately.
    • Step 4: If the emergency solution cannot be processed in step 3, the reject operation will be performed in step 4.
Several Notes: (I believe these online searches will be used. I will give a brief introduction here to pave the way for the future)
    • Block queue has the following implementations:
      1. arrayblockingqueue: bounded array queue
      2. Define blockingqueue: supports bounded/unbounded queues and is implemented using linked lists.
      3. priorityblockingqueue: priority queue, which can be sorted by task
      4. synchronousqueue: a queue with a queue length of 1. The difference between synchronousqueue and array is that submitting a client thread to the block queue is a blocking process until a worker thread connects to the poll task.
    • Rejectexecutionhandler is used for self-protection processing when the task cannot be processed:
      1. Reject directly throws a reject exception
      2. Discard directly ignores the runnable and cannot be obtained.
      3. discardoldest discards the earliest tasks in the queue.
      4. callsrun directly uses the original client thread as the worker thread for execution
Points that are easy to ignore: 1. After pool threads is started, subsequent tasks will be obtained through block queue to obtain accumulated runnable tasks. Therefore, we recommend that you: Block size> = corepoolsize, otherwise the thread pool will be meaningless 2. The difference between corepoolsize and maximumpoolsize is different from the database connection pool that everyone understands normally. * DBCP pool is used as an example to describe how to configure minidle and maxactive. Minidle represents the number of threads in the resident memory, and maxactive represents the maximum number of threads that work. * Corepoolsize is the maxactive concept of the connection pool. It does not have the minidle concept. (each thread can set KeepAliveTime. If there are more tasks than many times, the thread will be destroyed, but it does not always maintain a certain number of threads ). * Maximumpoolsize is the first level of an emergency measure. When the threadpoolexecutor's working threads is full and the block queue is full, it means it is close to the crash edge. In this case, a batch of threads can be set up temporarily to process runnable, and then exit immediately after processing. Therefore, we recommend that you: Maximumpoolsize> = corepoolsize = the expected maximum number of threads. (I have configured corepoolsize = 1, maximumpoolsize = 20, blockqueue is an unbounded queue, and finally it becomes a single-thread working pool. Typical configuration error) 3. Make good use of the combination of blockqueue and reject. Here we recommend the rejected handler of callsrun, which literally means that the caller can run it on his own. We often use some thread pools for asynchronous processing online. (Business Layer) Analysis and Design of Asynchronous Parallel loading technology, The original serial requests are changed to parallel operations, but too many parallel requests increase the system load (such as soft interruptions and context switching ). Therefore, you must set a size limit on the thread pool. However, in order to introduce asynchronous operations and avoid long wait time in the block queue, A callsrun policy must be executed when the queue is full, and parallel operations are converted into a serial processing, in this way, we can minimize the latency impact. Therefore, we recommend that you: Rejectexecutionhandler = callsrun, blockqueue size = 2 * poolsize) Reference: http://www.iteye.com/topic/1118660 More: Http://blog.csdn.net/waterbig/article/details/4794244 Http://rdc.taobao.com/team/jm/archives/595

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.