"java.util.concurrent and contract" the ThreadPool

Source: Internet
Author: User

One async with new Thread? Bigger "Low"!!
New Thread (new  Runnable () {@Overridepublicvoid  run () {//  TODO auto-generated method Stub}}). Start ();

You still use it up there, too low. A lot of drawbacks:

1. Each new thread creates a poor performance.

2. Threads lack unified management, may be unlimited new threads, compete with each other, and may consume excessive system resources resulting in freezing or oom.

3. Lack of more features, such as timed execution, periodic execution, and thread interruption.

This is in contrast to the benefits of the four thread pools provided by new Thread,java in the following ways:
1. Reuse existing threads, reduce the cost of object creation and extinction, and perform better.

2. Can effectively control the maximum number of concurrent threads, improve the utilization of system resources, while avoiding excessive resource competition, avoid clogging.

3. Provide the functions of timing execution, regular execution, single thread, concurrency control, etc.

24 Thread Pool Comparisons

Java provides four thread pools through executors, namely:

Newcachedthreadpool creates a cacheable thread pool that can flexibly reclaim idle threads (60s does not perform tasks) 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 executes tasks serially using only a single working thread, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority).

three bottom Java.util.concurrent.ThreadPoolExecutor

Regardless of which thread pool you create, you must call Threadpoolexecutor,?? Enumerate a construction method




When a task is added to the thread pool by the Execute (Runnable) method:

If the number of threads in the thread pool is less than corepoolsize at this point, even if the threads in the thread pool are idle, a new thread is created to handle the task being added.
If the number in the thread pool is equal to corepoolsize, but the buffer queue Workqueue is not full, then the task is placed in the buffer queue.
If the number of threads in the thread pool is greater than corepoolsize, the buffer queue Workqueue full, and the number of thread pools is less than maximumpoolsize, a new thread is built to handle the task being added.
If the number of threads in the thread pool is greater than corepoolsize, the buffer queue is workqueue full, and the number in the thread pool equals maximumpoolsize, the task is handled by handler the policy specified.

That is, the priority of the processing task is:
Core thread corepoolsize, Task queue workqueue, maximum thread maximumpoolsize, if all three are full, use handler to handle the rejected task.

When the number of threads in the thread pool is greater than corepoolsize, if a thread is idle for more than KeepAliveTime, the thread is terminated. This allows the thread pool to dynamically adjust the number of threads in the pool.

Deny policy:

four threadpoolexecutor source Analysis1. Fixedthreadpool

    • The Corepoolsize and maxiumpoolsize of Fixedthreadpool are set to the parameter nthreads specified when the Fixedthreadpool is created.
    • 0L means that when the number of threads in the thread pool is manipulating the number of core threads, the extra threads are immediately stopped
    • The last parameter indicates that Fixedthreadpool uses the unbounded queue Linkedblockingqueue as the worker queue for the thread pool, and because it is unbounded, when the thread pool threads reach Corepoolsize, the new task waits in the unbounded queue. So the thread pool has no more threads than corepoolsize, and Maxiumpoolsize becomes an invalid parameter, and the running thread pool does not reject the task.
    • Fixedthreadpool run diagram as follows

      The execution process is as follows:

      1. If the number of threads in the current work is less than the number of Corepool, a new thread is created to perform the task.

      2. When the number of threads in the thread pool's work reaches Corepool, the task is added to the linkedblockingqueue.

      3. When the thread finishes performing the tasks in 1, it will go from the queue to the task.

      Note Linkedblockingqueue is a unbounded queue, so you can always add new tasks to the thread pool.

2. Singlethreadexecutor

Singlethreadexecutor is a executor that uses a single worker thread. It is characterized by the use of a single worker thread to perform tasks . Its construction source is as follows:

Singlethreadexecutor's corepoolsize and Maxiumpoolsize are set to 1. The other parameters are the same as the Fixedthreadpool, with the following running diagram:

The execution process is as follows:

1. If the number of threads in the current work is less than the number of Corepool, create a new thread to perform the task.

2. When the number of threads in the thread pool's work reaches Corepool, the task is added to the linkedblockingqueue.

3. When the thread finishes performing the tasks in 1, it will go from the queue to the task.

Note: Because there is only one worker thread in the threads pool, the tasks can be executed in the order in which they were added.

3. Cachedthreadpool

Cachedthreadpool is an "unlimited" capacity thread pool that creates new threads as needed. The feature is that you can create new threads to perform tasks as needed without a specific corepool. Here's how it's constructed:

The corepoolsize of Cachedthreadpool is set to 0, that is, Corepool is empty, maximumpoolsize is set to Integer.max_value, that is, maximum is unbounded. Here the KeepAliveTime is set to 60 seconds, which means that idle threads can wait up to 60 seconds for the task, otherwise they will be recycled. Cachedthreadpool uses a synchronousqueue with no capacity as the work queue for the main thread pool, which is a blocking queue with no capacity. Each insert operation must wait for the corresponding remove operation from another thread. This means that if the main thread submits a task faster than the processing task in the thread pool, Cachedthreadpool will constantly create new threads. In extreme cases, Cachedthreadpool will run out of CPU resources because of multi-threaded creation. The operation diagram is as follows:

The execution process is as follows:

1. First Execute Synchronousqueue.offer (Runnable Task). If there are idle threads executing synchronousqueue.poll () in the current thread pool, then the offer operation performed by the primary thread is paired successfully with the poll operation performed by the idle thread, and the main thread takes the task to the idle thread for execution. , execute () method executes successfully, otherwise perform step 2

2. When the thread pool is empty (the initial maximumpool is empty) or there is no idle thread, the pairing fails and no thread will perform the synchronousqueue.poll operation. In this case, the line pool creates a new thread to perform the task.

3. After the new thread is created, the poll operation is performed. When the thread of step 2 finishes, it waits 60 seconds, and if the main thread commits a new task, the idle thread will perform a new task or be recycled. Therefore, a cachedthreadpool that does not commit a task for a long time does not consume system resources.

Synchronousqueue is a block queue that does not store elements, and you must wait for the poll action each time an offer operation is made, or you cannot continue adding elements.

4. Call New Threadpoolexecutor manually

"java.util.concurrent and contract" the ThreadPool

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.