Concurrent Programming (ii): Thread pool

Source: Internet
Author: User

Compared to the thread pool, we might touch new thread a bit more, since we have the new thread, why do we use the thread pool?

The disadvantage of new thread

A, each new thread to create an object, poor performance

b, the thread lacks the unified management, may the unrestricted new thread, competes with each other, may occupy excessive system resources to cause the freezing or oom (OutOfMemory)

C, lack of more features, such as more execution, periodic execution, thread interruption

Benefits of the thread pool

A, the reuse of existing threads, reduce the creation of objects, the cost of extinction, good performance

b, can effectively control the maximum number of concurrent threads, improve system resource utilization, while avoiding excessive resource competition, to avoid blocking

C, provide timing execution, regular execution, single-threaded, concurrency control and other functions

Thread Pool class diagram

As can be seen from the class diagram, the Threadpoolexecutor class is the most central class in the thread pool. Let's do the key analysis.

Threadpoolexecutor Construction Parameters

A, Corepoolsize: number of core threads, by default (can be pre-created thread) thread pool The number of threads is 0, when there is a task after the task will create a thread to perform the task, when the number of threads in the thread pool reaches Corepoolsize, will put the incoming task into the cache queue.

B, maximumpoolsize: Thread maximum thread count

C, WorkQueue: Block queue, store waiting to perform the task, there are three kinds of values, Arrayblockqueue (based on an array of FIFO queue, the creation must specify the size), Linkedblockingqueue (List-based FIFO queue, If this queue size is not specified, default is Integer.max_value), Synchronousqueue (the submitted task is not saved, a new thread is created directly to perform the task)

D, KeepAliveTime: Threads do not have the maximum time to terminate when a task is executed, by default, KeepAliveTime only works when the number of threads in the thread pool is greater than corepoolsize, and when the number of threads in the thread pool is greater than corepoolsize, If the idle time of a thread reaches KeepAliveTime, it terminates. If you call the Allowcorethreadtimeout (Boolean) method, the KeepAliveTime parameter also works when the number of threads in the thread pool is not greater than corepoolsize, until the thread pool has 0 threads

E, Unit:keepalivetime time unit, there are 7 values, such as: timeunit.days; Days, can be specific to nanoseconds

F, threadfactory: Thread factory, used to create threads

G, Rejecthandler: When a policy is rejected when processing a task, there are usually four kinds of values, Threadpoolexecutor.abortpolicy: Discarding the task and throwing a rejectedexecutionexception exception ; Threadpoolexecutor.discardpolicy: Discards the task, but does not throw an exception; Threadpoolexecutor.discardoldestpolicy: Discards the task that precedes the queue, Retry the task (repeat this process); Threadpoolexecutor.callerrunspolicy: The task is handled by the calling thread

The relationships between the parameters are as follows:

A, if the current poolsize is less than corepoolsize, create a new thread to perform the task

b, if the current poolsize is greater than corepoolsize, and the waiting queue is not full, enter the waiting queue

C, if the current poolsize is greater than corepoolsize and less than maximumpoolsize, and the waiting queue is full, create a new thread to perform the task

D, if the current poolsize is greater than corepoolsize and is greater than maximumpoolsize, and the wait queue is full, use a deny policy to process the task

E, threads in the thread pool do not exit immediately after executing a task, but instead check to see if the waiting queue has a new thread to execute, and if the new task is not keepalivetime, the thread exits

Threadpoolexecutor status

It is important to note the difference between the shutdown () and the Shutdownnow () methods, which are executed after the thread is executed and then closed, the thread pool shuts down immediately after executing the latter, and the executing threads are no longer executing

Threadpoolexecutor method

A, execute (): Submit task to thread pool execution

B, Submit (): Submit the task and be able to return to the execution result execute+future

C, Shutdown (): Close the thread pool and wait for the task to finish executing

D, Shutdownnow (): Closes the thread pool without waiting for the task to finish executing

E, Gettaskcount (): Total number of tasks performed and not performed by the thread pool

F, Getcompletedtaskcount (): Number of tasks completed

G, Getpoolsize (): Thread pool When the number of front threads

H, Getactivecount (): The number of threads that the current thread pool is performing tasks on

Executors class

As can be seen from the class diagram above, the Executors class provides some tool methods for Executor,executorservice,scheduledexecutorservice, And executors encapsulates the Scheduledthreadpoolexecutor class and the Threadpoolexecutor class, so we advocate the use of this class in practice, and the Executors class provides four static methods:

A, Newcachedthreadpool: Create a cacheable thread pool, flexibly reclaim idle threads, and create a new thread if there are no recyclable threads

As can be seen, Newcachedthreadpool set Corepoolsize to 0, set Maximumpoolsize to Integer.max_value, use Synchronousqueue, That means there's a new task. The thread is destroyed when the thread is idle for more than 60 seconds. The demo code is as follows:

  Public Static voidMain (string[] args) {Executorservice Executorservice=Executors.newcachedthreadpool ();  for(inti = 0; I < 10; i++) {            Final intindex =i; Executorservice.execute (NewRunnable () {@Override Public voidrun () {Log.info ("Task:{}", index);        }            });    } executorservice.shutdown (); }

B, Newfixedthreadpool: Create a thread pool to control the maximum number of concurrent threads, and the excess threads will wait in the queue

The thread pool created by Newfixedthreadpool is equal to the value of Corepoolsize and Maximumpoolsize, and the threads are destroyed directly after idle, using Linkedblockingqueue. The demo code is as follows:

 Public Static voidMain (string[] args) {Executorservice Executorservice= Executors.newfixedthreadpool (3);  for(inti = 0; I < 10; i++) {            Final intindex =i; Executorservice.execute (NewRunnable () {@Override Public voidrun () {Log.info ("Task:{}", index);        }            });    } executorservice.shutdown (); }

C, Newscheduledthreadpool: Create size unlimited thread pool (max. Integer.max_value), support timed and recurring task execution

Newscheduledthreadpool is characterized by the ability to schedule tasks, The most common method is scheduleatfixedrate (task scheduling based on fixed time interval) and Schedulewithfixeddelay (task scheduling based on an interval of time, depending on the duration of the task execution), the demo code is as follows:

  Public Static voidMain (string[] args) {Scheduledexecutorservice Executorservice= Executors.newscheduledthreadpool (5); Executorservice.schedule (NewRunnable () {@Override Public voidrun () {Log.warn ("Schedule Run"); }        },3, Timeunit.seconds); Executorservice.scheduleatfixedrate (NewRunnable () {@Override Public voidrun () {Log.warn ("Schedule Run"); }        },1,3, Timeunit.seconds); }

  

D, Newsinglethreadexecutor: Create a single threaded thread pool that performs tasks with only a single thread

Newsinglethreadexecutor the corepoolsize and maximumpoolsize are fixed to 1, the thread is destroyed directly when idle, and the Linkedblockingqueue.demo code used is as follows:

  Public Static voidMain (string[] args) {Executorservice Executorservice=Executors.newsinglethreadexecutor ();  for(inti = 0; I < 10; i++) {            Final intindex =i; Executorservice.execute (NewRunnable () {@Override Public voidrun () {Log.info ("Task:{}", index);        }            });    } executorservice.shutdown (); }

Reasonable configuration of thread pool

The specific coordination of the thread pool needs to be adjusted according to the actual situation, the following two reference principles, can be set according to the principle of the system load, the use of resources to adjust.

A, CPU-intensive tasks, the need to squeeze the CPU as much as possible, the reference value can be set to ncpu+1;

b, IO-intensive tasks, reference values can be set to 2*NCPU

Concurrent Programming (ii): Thread pool

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.