Java concurrency Programming in layman's terms (i): Usage of thread pool

Source: Internet
Author: User

We build a thread when we use threads, which is very easy to implement, but there is a problem:

If the number of concurrent threads is large, and each thread is performing a short task for a period of time, then the frequent creation of threads can greatly reduce the efficiency of the system.

So how to solve this kind of problem?

In Java, this effect can be resolved through the thread pool. The previous article briefly mentions the use of thread pools. Today we are going to explain in detail the Java thread pool, from easy and difficult, step on, steps are as follows:

    • First, we start with the core Threadpoolexecutor class approach.

    • And then tell me how it's implemented.

    • The corresponding example is then given.

    • Finally we discuss how to reasonably configure the size of the thread pool



First, the Threadpoolexecutor class in Java

Before we get to know the Threadpoolexecutor class, let's take a look at Threadpoolexecutor's specific implementation source code.

package java.util.concurrent;import java.util.concurrent.locks.*;import java.util.*;p ublic  class threadpoolexecutor extends abstractexecutorservice { ....//here only gives the source of the constructor,  public threadpoolexecutor (int corepoolsize,int maximumpoolsize,                                long keepAliveTime,TimeUnit unit,                                blockingqueue<runnable> workqueue)  {         this (Corepoolsize, maximumpoolsize, keepalivetime,  unit, workQueue,              Executors.defaultthreadfactory (), &NBsp;defaulthandler);     }public threadpoolexecutor (Int corepoolsize, int  maximumPoolSize,                               long  keepalivetime,timeunit unit,                                blockingqueue<runnable> workqueue,                                threadfactory threadfactory)  {        this ( corepoolsize, maximumpoolsize, keepalivetime, unit, workqueue,            &nBsp; threadfactory, defaulthandler);     }public threadpoolexecutor (int  corePoolSize,int maximumPoolSize,                                long keepAliveTime,TimeUnit unit,                                BlockingQueue<Runnable> workQueue,                                rejectedexecutionhandler handler)  {         this (corepoolsize, maximumpoolsize, keepalivetime, unit, workqueue,        &Nbsp;     executors.defaultthreadfactory (),  handler);     }  public threadpoolexecutor (int corepoolsize,int maximumpoolsize,                                long keepAliveTime,TimeUnit unit,                                BlockingQueue<Runnable> workQueue,                                ThreadFactory threadFactory,                          &nbSp;     rejectedexecutionhandler handler)  {         if  (corepoolsize < 0 | |             maximumpoolsize <= 0  | |             maximumPoolSize <  corepoolsize | |             keepalivetime < 0)              throw new illegalargumentexception ();        if  (workqueue == null | |  threadfactory == null | |  handler == null)             throw  new nullpointerexception ();         this.corepoolsize =  corepoolsize;        this.maximumpoolsize = maximumpoolsize;         this.workQueue = workQueue;         this.keepalivetime = unit.tonanos (KeepAliveTime);         this.threadFactory = threadFactory;         this.handler = handler;    }}

As you can see from the code above, the Threadpoolexecutor that inherits the Abstractexecutorservice class listens to four constructors, but finally executes the fourth constructor

publicThreadPoolExecutor(int corePoolSize,intmaximumPoolSize,longkeepAliveTime,TimeUnit unit,        BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler);

Where Corepoolsize: The size of the core pool, after the thread pool is created, there are no threads by default, but wait for the task to arrive before creating the threads. The meaning of this parameter: when the thread pool data reaches corepoolsize, it will put the arriving task into the cache queue.

Maximumpoolsize: The maximum number of threads in the thread pool, representing the maximum number of threads that can be created in the threads pool;

KeepAliveTime: Indicates the maximum length of time a thread will be terminated without a task executing.

Unit: The time unit of the parameter KeepAliveTime.

WorkQueue: A blocking queue that stores tasks waiting to be executed

Threadfactory: Thread factory, primarily used to create threads

Handler: Represents a policy when a task is rejected, primarily

Threadpoolexecutor.abortpolicy: Discards the task and throws a rejectedexecutionexception exception. Threadpoolexecutor.discardpolicy: Also discards the task, but does not throw an exception. Threadpoolexecutor.discardoldestpolicy: Discards the first task in the queue and then tries to perform the task again (repeating this procedure) Threadpoolexecutor.callerrunspolicy: The task is handled by the calling thread

There are several very important methods in the Threadpoolexecutor class:

Execute () Submit () shutdown () Shutdownnow ()

The Execute () method is actually the method declared in Threadpoolexecutor's great-grandfather class executor, which is implemented in Threadpoolexecutor, and this method is the core method of Threadpoolexecutor , this method can submit a task to the thread pool to be executed by the thread pool.

The Submit () method is a method declared in Executorservice, which has a specific implementation in Abstractexecutorservice and is not overridden in threadpoolexecutor. This method is also used to submit a task to the thread pool, but unlike the Execute () method, it can return the result of the task execution and see the implementation of the Submit () method, and it will actually be called the Execute () method. But it uses the future to get the results of the task execution.

Shutdown () and Shutdownnow () are used to close the thread pool.

Use example:

Public class test {     public static void main (String[ ] args)  {            threadpoolexecutor  executor = new threadpoolexecutor (5, 10, 200, timeunit.milliseconds,                  new  Arrayblockingqueue<runnable> (5));                    for (int i=0;i<15;i++) {              mytask mytask = new mytask (i);              executor.execute (MyTask);    &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN (thread pool number of threads: "+ Executor.getpoolsize () + ", Number of tasks waiting to be executed in queue:" +&nbSp;            executor.getqueue (). Size () + ", Number of other tasks performed: "+executor.getcompletedtaskcount ());         }          executor.shutdown ();     }}   class MyTask implements Runnable {    private int  Tasknum;         public mytask (Int num)  {         this.taskNum = num;    }           @Override     public void run ()  {         system.out.println ("Executing task " +taskNum);         try {             thread.currentthread (). Sleep (4000);        } catch  (interruptedexception e)  {             e.printstacktrace ();         }        system.out.println ("task " +tasknum+ "execution completed");     }}

But in Java doc and we recommend that we use Threadpoolexecutor directly instead, we use several static methods provided in the Executors class to create the thread pool

Executors.newcachedthreadpool ();   Create a buffer pool with buffer pool capacity of Integer.MAX_VALUEExecutors.newSingleThreadExecutor ();    Create a buffer pool executors.newfixedthreadpool (int) with a capacity of 1; Create a buffer pool of fixed capacity size

For specific examples, please refer to: http://aku28907.blog.51cto.com/5668513/1773073

2, how to properly configure the size of the thread pool

It is generally necessary to configure the thread pool size according to the type of task:

For CPU-intensive tasks, you need to squeeze the CPU as much as possible, and the reference value can be set to Ncpu+1

If it is an IO-intensive task, the reference value can be set to A/NCPU

Of course, this is only a reference value, the specific settings also need to adjust according to the actual situation, such as the thread pool size can be set to reference values, and then observe the task run and system load, resource utilization to make appropriate adjustments.

Tasks of a different nature can be handled separately by thread pools of different sizes. CPU-intensive tasks configure as few threads as possible, such as configuration ncpu+1 thread pool of threads. IO-intensive tasks are not always performing tasks because they need to wait for IO operations, so configure as many threads as possible, such as 2*n cpu Mixed-type tasks, if they can be split into a CPU-intensive task and an IO-intensive task, as long as the time difference between the two tasks is not too large, then the throughput rate after decomposition is higher than the serial execution throughput rate, if the two task execution time is too large, it is not necessary to decompose. We can get the number of CPUs for the current device through the Runtime.getruntime (). Availableprocessors () method.

Tasks with different priority levels can be handled using the priority queue Priorityblockingqueue. It allows high-priority tasks to be executed first, and it is important to note that low-priority tasks may never be executed if a task with a high priority is committed to the queue.

Tasks with different execution times can be handled by different sizes of thread pools, or priority queues can be used to perform tasks that have a short execution time.

A task that relies on the database connection pool, because the thread submits the SQL and waits for the database to return the results, and the longer the CPU idle time waits, the greater the number of threads should be, so that the CPU can be better utilized.

It is recommended to use bounded queue , the bounded queue can increase the stability and early warning ability of the system, can be set to a larger point, such as thousands of. One time the queue and thread pool of the background task thread pool used by our group were full, and threw out the exception of the task, and by finding out that there was a problem with the database, the execution of SQL became very slow, because the tasks of the background task line constructor all needed to query and insert data into the database. So the work thread that causes the line constructor all blocks, the task backlog is constructor online. If we were to set up the unbounded queue, the thread pool would have more and more queues, potentially filling up the memory, making the whole system unusable, not just a background task. Of course all our system tasks are deployed with separate servers, and we use thread pools of different sizes to run different types of tasks, but this problem can also affect other tasks.



This article is from the "Ah Cool blog source" blog, please make sure to keep this source http://aku28907.blog.51cto.com/5668513/1775415

Java concurrency Programming in layman's terms (i): Usage of 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.