Custom thread pool-threadpoolexecutor

Source: Internet
Author: User

Example method:

Protected executorservice createexecutorservice (){

Return new threadpoolexecutor (corepoolsize, maximumpoolsize, KeepAliveTime, unit, workqueue, threadfactory );

}

I hope that my friends here can quietly read the official explanations below. I don't think I'm lazy, but I think the official explanation below can better express what I mean.

The thread pool can solve two different problems: because it reduces the overhead of each task call, they can generally provide enhanced performance when executing a large number of asynchronous tasks, you can also bind and manage resources (including the threads used to execute collection tasks. EachThreadpoolexecutorSome basic statistics, such as the number of completed tasks, are also maintained.

This class provides many adjustable parameters and extension hooks for ease of use across a large number of contexts. However, it is strongly recommended thatProgramEasy to useExecutorsFactory methodExecutors. newcachedthreadpool ()(The unbounded thread pool can be used for automatic thread recovery ),Executors. newfixedthreadpool (INT)(Fixed size thread pool) andExecutors. newsinglethreadexecutor ()(Single background thread), which are predefined for most use cases. Otherwise, use the following instructions when manually configuring and adjusting the class:

Core and maximum pool size
ThreadpoolexecutorAccording to corepoolsize (see Getcorepoolsize ()) And maximumpoolsize (see Getmaximumpoolsize ()) Sets the boundary to automatically adjust the pool size. When the new task is in Execute (Java. Lang. runnable)When submitting, if the number of running threads is less than corepoolsize, a new thread is created to process the request, even if other auxiliary threads are idle. If the number of running threads is greater than corepoolsize and less than maximumpoolsize, a new thread is created only when the queue is full. If the set corepoolsize and maximumpoolsize are the same, a fixed thread pool is created. If you set maximumpoolsize to a basic unbounded value (for example Integer. max_value), The pool is allowed to adapt to any number of concurrent tasks. In most cases, the core and maximum pool sizes are only set based on the constructor, but you can also use Setcorepoolsize (INT)And Setmaximumpoolsize (INT)Make dynamic changes.
Construct on demand
By default, you can use Prestartcorethread ()Or Prestartallcorethreads ()Rewrite it dynamically.
Create a thread
Use ThreadfactoryCreate a new thread. Otherwise ThreadgroupAll in use Executors. defaultthreadfactory ()Create threads, and these threads have the same Norm_priorityPriority and non-daemon status. By providing different threadfactory, you can change the thread name, thread group, priority, and daemon status. If NewthreadReturn null ThreadfactoryIf a thread cannot be created, the program continues to run, but no task can be executed.
Maintain activity time
If there are more threads in the pool than corepoolsize, these extra threads will be terminated when the idle time exceeds KeepAliveTime (see Getkeepalivetime (Java. util. Concurrent. timeunit)). This provides a way to reduce resource consumption when the pool is inactive. If the pool becomes more active later, a new thread can be created. You can also use Setkeepalivetime (long, java. util. Concurrent. timeunit)Modify this parameter dynamically. Use Long. max_value Timeunit. nanosecondsThe value of can effectively disable idle threads from the previous termination status before closing.
Queuing
All Blockingqueue Can be used to transfer and maintain submitted tasks. You can use this queue to interact with the pool size:

    • If the number of running threads is less than corepoolsize, executor always prefers to add new threads without queuing.
    • If the running thread is equal to or greater than corepoolsize, executor always prefers to add requests to the queue without adding new threads.
    • If the request cannot be added to the queue, a new thread is created, unless the creation of this thread exceeds the maximumpoolsize. In this case, the task is denied.

There are three common queuing policies:

    1. Submit directly.The default Job Queue option isSynchronousqueueIt directly submits tasks to the thread without holding them. If there is no thread that can be used to run the task immediately, trying to add the task to the queue will fail, so a new thread will be constructed. This policy prevents locking when processing a collection of requests that may have internal dependencies. Direct submission usually requires unbounded maximumpoolsizes to avoid rejecting new tasks. This policy allows unbounded threads to grow when the command arrives continuously beyond the average number that the queue can handle.
    2. Unbounded queues.Use unbounded queues (for exampleLinkedblockingqueue) Will cause new tasks to be added to the queue when all corepoolsize threads are busy. In this way, the created thread will not exceed the corepoolsize. (Therefore, the value of maximumpoolsize is invalid .) When each task is completely independent from other tasks, that is, task execution does not affect each other, it is suitable to use unbounded queues. For example, in a Web Page Server. This kind of queuing can be used to handle transient bursts of requests. This policy allows unbounded threads to grow when the command arrives continuously beyond the average number that the queue can handle.
    3. Bounded queue.When a limited maximumpoolsizes is used, a bounded Queue (suchArrayblockingqueue) Helps prevent resource depletion, but may be difficult to adjust and control. The queue size and the maximum pool size may need to be compromised: using large queues and small pools can minimize CPU usage, operating system resources, and context switching overhead, but may cause manual throughput reduction. If the tasks are frequently congested (for example, if they are I/O boundaries), the system may schedule a longer time than you permit for more threads. Using a small queue usually requires a large pool size, and the CPU usage is high, but it may encounter unacceptable scheduling overhead, which will also reduce the throughput.

What about the official explanation of the classic network!

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.