Java Threading API Learning thread pool Threadpoolexecutor (GO)

Source: Internet
Author: User


Thread pool Threadpoolexecutor inherits from Executorservice. is a new feature added by jdk1.5, which executes the committed task in an available thread in the internal thread pool. constructor function

Threadpoolexecutor (int  corepoolsize,                                 int  maximumpoolsize,                                 Long  KeepAliveTime,                                 timeunit unit,                                 blockingqueue<Runnable> workQueue,                                 Threadfactory threadfactory,                                 rejectedexecutionhandler handler)  

Corepoolsize

the number of core threads maintained by the thread pool. Why does this say that the number of core threads instead of the minimum number of threads is because the online pool is created and does not create corepoolsize threads directly, but is created temporarily when a task arrives. When Corepoolsize threads are created as needed, the number of threads is not reclaimed by the thread pool, even when they are idle. This value can then be understood as the minimum number of threads maintained by the thread pool. maximumpoolsizethe maximum number of threads maintained by the thread pool. KeepAliveTimewhen the number of threads in the thread pool is greater than corepoolsize, the extra number of threads that are idle KeepAliveTime will be retracted. Unithe time unit of the KeepAliveTime. The optional parameters are several static properties in Java.util.concurrent.TimeUnit: nanoseconds, microseconds, MILLISECONDS, SECONDS. WorkQueuea queue that holds the tasks that are submitted to the thread for execution by the Execute method. threadfactorythe factory responsible for creating threads to the thread pool. HandlerThe processing policy that is executed when the queue reaches its limit causing the task to block. Handler has four options: Threadpoolexecutor.abortpolicy (throws a Java.util.concurrent.RejectedExecutionException exception). Threadpoolexecutor.callerrunspolicy (retry adding the current task, he will automatically repeatedly call the Execute method). Threadpoolexecutor.discardoldestpolicy (abandon the old task). Threadpoolexecutor.discardpolicy (Discard the current task). For general applications, instead of creating a thread pool through constructors, we use encapsulated tool methods that set the default values for most parameters. Constructors are used directly only if there is a higher requirement for the attributes of the thread pool. Executors.newcachedthreadpool (creates a thread pool that automatically increases or decreases capacity) Executors.newfixedthreadpool (creates a fixed-capacity thread pool) Executors.newsinglethreadexecutor (thread pool for separate threads). Here are some advanced features corepoolsize and maximumpoolsize Threadpoolexecutor Adjust the number of threads in the thread pool based on the values of Corepoolsize and maximumpoolsize. When a new task is submitted to the thread pool through the Threadpoolexecutor.execute method, if the thread pool is less than corepoolsize in number of threads, a thread is created to perform the task even if it is idle, and if the thread pool is more than corepoolsize and the number of front threads is Less than maximumpoolsize, a new thread is created only if the available threads are not enough. If you do not want the system to dynamically increase or decrease the number of threads, set the corepoolsize and Maximumpoolsize values to the same value. If you set maximumpoolsize to a particularly large value such as Integer.max_value, Threadpoolexecutor becomes a thread pool that can accommodate a large number of concurrent tasks. Generally speaking, corepoolsize and Maximumpoolsize are set when the Threadpoolexecutor object is constructed and can still be called Threadpoolexecutor.setcorepoolsiThe Ze and Threadpoolexecutor.setmaximumpoolsize methods modify both properties.
about threads created in thread pool are created by Threadfactory. If not specified, Executors.defaultthreadfactory is used to create a non-daemon thread that is in the same thread group, with the same priority (Norm_priority). If you specify Threadfactory, you can customize the thread name, thread group, priority, whether it is a daemon thread, and so on. start creating threads until needed by default, the online pool is just created and no threads exist. Until a task is submitted to the thread pool. You can change the default behavior by using the Threadpoolexecutor.perstartcorethread or Threadpoolexecutor.prestartallcorethreads method.
the lifetime of a thread if the current number of threads in the thread pool is greater than corepoolsize, if it is not used after keepalivetime, the excess will be terminated. Re-create when more threads are needed. This property can also be modified by Setkeepalivetime.
calling the Threadpoolexecutor.execute method to submit a new task, if the thread pool has been stopped running or the number of threads, the number of queues is full, Rejectedexecutionhandler.rejectedexecution is called. ================================================================================ ============= All of the above is a bit abstract, it really has to be in use when carefully studied. However, it is necessary to remember the basic logic of this thread pool processing if you want to be able to meet the problem. Here's a real-life example to help you understand. We can think of a thread pool (threadpoolexecutor) as a department of the company A (executors.newcachedthreadpool): This department is responsible for handling the tasks assigned from the Customer (Task). At the beginning of the department, the Human resources department set the upper limit (maximumpoolsize=60) and the lower limit (corepoolsize=0), and asked the department manager to wait until the first task arrived to recruit the first team member (until needed to create a thread). Department also developed a work of their own, that is, we can not make the task backlog! When the department is set up, the task is assigned from the client side, and the department manager recruits an employee for each task. When the employee finishes the work at hand, the department manager takes a break for them for a period of time (KeepAliveTime). After the recuperation of the staff, the spirit of waiting for the manager to give you the task of continuing to work happily. However, this period of economic downturn, not so much work needs to be done, in the cost-saving consideration, the company will not work non-core employees (because Corepoolsize=0, so the department does not have core staff) dismissed. By the end of the year, more and more work, department managers continue to recruit, until the number of departments reached the ceiling, every employee is desperately working without a breath of opportunity. Another task was assigned to the Commiseration department, which became the last straw in the crushing department. The department manager was overwhelmed and decided to protest: We can't do more work (AbortPolicy)! B (Executors.newfixedthreadpool): This department is responsible for handling tasks assigned from the Customer (Task). At the beginning of the department's establishment, the Human resources department set the lower limit of departmental personnel (corepoolsize). and ask the department manager to wait until the first task arrives to recruit the first member (until needed to create a thread). The department has also worked out a working schedule, that is, we must not be able to make the task backlog too much (linkedblockingqueue.capacity)! When the department is set up, the task is assigned from the client side, and the department manager recruits an employee for each task. Wait until the number of departments to reach the lower limit of departmental staff can no longer recruit. Redundant tasks will be shelved in the backlog list, and other tasks can be completed one after another. Since the department is a core employee, it's important not to worry about being fired. When a task assigned to a department hits the upper limit of the backlog, the department manager called out to say: we can not do more work (AbortPolicy)! The staff floor of this department can be set up, in extreme cases the department has only one employee (executors.newsinglethreadexecutor). Later, the company felt that if sent to the Department of the task too much, the department manager just jumped out to shout the refusal is a little too simple, should allow him to do more things to defuse the crisis. So the department manager gradually learned to Threadpoolexecutor.callerrunspolicy (retry adding the current task, he will automatically repeat the call to the Execute method). Threadpoolexecutor.discardoldestpolicy (abandon the old task). Threadpoolexecutor.discardpolicy (Discard the current task). This shows that the threadpoolexecutor thread pool, taking into account the ease of use and expansion of flexibility. For general use, executors is sufficient. If the threadfactory, rejectedexecutionhandler,blockingqueue different to achieve a flexible combination, but also to meet the needs of a variety of situations really do for everyone. ================================================================================================by the way, multithreading master Doug Lea. The author of the Java.util.concurrent package.

If it's history is connected by human subjects, Doug Lea must be the one. The bridge of the nose, with his glasses, and the beard of King Wilhelm Ii., with a humble, shy smile on his face, serves the grandfather of the computer science department at the State University of New York Oswego. That he is the most influential person in the world to Java, not at all. Because two times in the history of the great changes in Java, he has indirectly or directly played a pivotal role in the color. One of the most important new initiatives from JDK 1.1 to JDK 1.2,jdk1.2 is collections, whose collection concept can be inherited from Doug Lea's first widely used collections released in 1995. ; one was Tiger launched in 2004. Tiger has 15 JSRs (Java specification requests) syntax and standards, one of which is JSR-166. JSR-166 is a util.concurrent package from Doug. It is worth mentioning that Doug Lea is also a member of the JCP (Java Community Project). Doug is a selfless person, he knows that sharing knowledge and sharing apple is not the same, Apple will forewarned less, and their knowledge will not be reduced because of the others, the sharing of knowledge can be stirred up a different spark. Joshua Blosh, author of the Java classics of effective Java, is particularly thankful that Doug is the soundboard of many of the ideas in this book, thanks to Doug for sharing his rich and valuable knowledge. http://blog.csdn.net/ABBuggy/archive/2011/06/16/6548843.aspxhttp://www.cnblogs.com/abbuggy/archive/2011/06/16/2594251.html

Java Threading API Learning thread pool Threadpoolexecutor (GO)

Related Article

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.