Java multithreaded learning thread pool detailed

Source: Internet
Author: User

0. The need to use a thread pool

? In a production environment, if you assign one thread to each task, you can cause many problems:

    1. the cost of the thread life cycle is very high. threads can be created and destroyed at a cost. For example, the creation of threads takes time and delays processing requests. If the requested arrival rate is very high and the processing of the request is lightweight, creating a thread for each request consumes a lot of computer resources.
    2. resource consumption. an active thread consumes system resources, especially memory. If the number of threads that can be run is greater than the number of processors, some threads are idle. Idle threads consume memory, put pressure on the garbage collector, and incur additional performance overhead when a large number of threads compete with the CPU.
    3. stability. A OutOfMemory exception can occur if the number of threads is too large.
1. The Threadpoolexecutor class in Java

? java.uitl.concurrent.ThreadPoolExecutorclasses are the most core classes in a thread pool, so you must understand this class in depth if you want to understand the thread pool in Java. Let's look at the source code of the Threadpoolexecutor class. There are four construction methods available in the Threadpoolexecutor class:

 PublicThreadpoolexecutor (intCorepoolsize,intMaximumpoolsize,LongKeepAliveTime, Timeunit unit, blockingqueue<runnable> work Queue) { This(Corepoolsize, Maximumpoolsize, KeepAliveTime, Unit, WorkQueue, executors.)defaultthreadfactory(), DefaultHandler); } PublicThreadpoolexecutor (intCorepoolsize,intMaximumpoolsize,LongKeepAliveTime, Timeunit unit, blockingqueue<runnable> work Queue, Threadfactory threadfactory) { This(Corepoolsize, Maximumpoolsize, KeepAliveTime, Unit, WorkQueue, Threadfactory, DefaultHandler); } PublicThreadpoolexecutor (intCorepoolsize,intMaximumpoolsize,LongKeepAliveTime, Timeunit unit, blockingqueue<runnable> work Queue, Rejectedexecutionhandler handler) { This(Corepoolsize, Maximumpoolsize, KeepAliveTime, Unit, WorkQueue, executors.)defaultthreadfactory(), handler); } PublicThreadpoolexecutor (intCorepoolsize,intMaximumpoolsize,LongKeepAliveTime, Timeunit unit, blockingqueue<runnable> work Queue, Threadfactory threadfactory, Rejectedexecutionhandler Han Dler) {if(Corepoolsize <0|| Maximumpoolsize <=0||            Maximumpoolsize < Corepoolsize | | KeepAliveTime <0)Throw NewIllegalArgumentException ();if(WorkQueue = =NULL|| Threadfactory = =NULL|| Handler = =NULL)Throw NewNullPointerException (); This.corepoolsize= Corepoolsize; This.maximumpoolsize= Maximumpoolsize; This.WorkQueue= WorkQueue; This.KeepAliveTime= unit.Tonanos(KeepAliveTime); This.threadfactory= Threadfactory; This.Handler= handler; }

Parameter description:

    • Corepoolsize: Core pool size. After the thread pool is created, by default, there are no threads in the thread pools, but instead wait for the task to come up and create the thread to perform the task. You can also call the Prestartallcoret hreads () or the prestartcorethread () method ahead of time to create a corepoolsize thread or a thread in advance. By default, the thread pool is created after the number of threads is 0, and when a task is committed, a thread is created, and when the thread reaches Corepoolsize, the newly committed task is placed in the cache queue.

    • Maximumpoolsize: The maximum number of threads in the thread pool, representing the maximum amount of threads that can be created in the thread pools. When the cache queue is full, the newly committed task creates a new thread execution until Maximumpoolsize threads are reached in the thread pool.

    • KeepAliveTime: Indicates that the thread has no maximum time to live when the task executes. By default, the thread pool will only take effect if the number of threads is greater than corepoolsize, meaning that other threads with extra corepoolsize will be able to survive for a limited time or Allowcorethreadtimeout (true) The method sets the time limit for all threads in the thread pool to survive.

    • Unit: The unit of survival time, in the following units:

  TimeUnit.DAYS;               //天  TimeUnit.HOURS;             //小时  TimeUnit.MINUTES;           //分钟  TimeUnit.SECONDS;           //秒  TimeUnit.MILLISECONDS;      //毫秒  TimeUnit.MICROSECONDS;      //微妙  TimeUnit.NANOSECONDS;       //纳秒
    • WorkQueue: Blocking queue, for temporary storage of tasks, there are several:
  ArrayBlockingQueue;  LinkedBlockingQueue;  SynchronousQueue;
    • Threadfactory: Thread factory, specifying the policy to create the thread.

    • Handler: A strategy for processing when tasks cannot be processed and stored in a timely manner. For example, the thread pool is full and the blocking queue is full, and the newly submitted task needs to be processed. The following treatment scenarios:

    • Terminate (abort) policy
      • ThreadPoolExecutor.AbortPolicy: The default saturation policy, which throws an unchecked rejectedexecutionexception exception, and the caller needs to handle this exception.
      • ThreadPoolExecutor.DiscardPolicy: Also discards the task, but does not throw an exception.
      • ThreadPoolExecutor.DiscardOldestPolicy: Discards the next task that is about to be executed, and then attempts to resubmit the task. If the work queue is set to a priority queue, then the task with the highest priority (Discard) will be discarded, which is obviously unreasonable.
    • "caller Run (caller-runs)" policy
      • ThreadPoolExecutor.CallerRunsPolicy: The policy does not discard the task, nor throws an exception, but instead rolls the task back to the caller, which has the caller thread to execute the thread. Because the caller thread takes a certain amount of time to execute the task, during that period, the caller thread is unable to accept other tasks, and the threads in the thread pool are seeking execution time. In a Web server, requests that arrive during this period are saved in the TCP layer's queue instead of in the application's queue. If the TCP layer queue is overloaded with persistent overloads, he will start discarding the request. Thus, if the server is overloaded, the pressure will spread out: from the thread pool's message queue to the application to the TCP layer, eventually reaching the client, causing the server to slow down in a high-load situation.
2. The status of the thread pool

? A set of variables is defined in Threadpoolexecutor that represents the status of the thread pool:

//Private Static Final intCount_bits = Integer.SIZE-3;//numbers made up of 28 x 12 binaryPrivate Static Final intCapacity = (1<< count_bits)-1;//runstate is stored in the High-order bitsPrivate Static Final intRUNNING =-1<< count_bits;Private Static Final intSHUTDOWN =0<< count_bits;Private Static Final intSTOP =1<< count_bits;Private Static Final inttidying =2<< count_bits;Private Static Final intTERMINATED =3<< count_bits;//Packing and unpacking ctlPrivate Static int runstateof(intc) {returnC & ~capacity; }
    1. When the thread pool is created, the RUNNING state;
    2. If the SHUTDOWN () method is called, then the thread pool is in the SHUTDOWN state, and the line pool is not able to accept the new task, and it waits for all tasks to complete;
    3. If the Shutdownnow () method is called, the thread pool is in the STOP state, and this time, the thread pools are unable to accept new tasks, and will attempt to terminate the task being performed;
    4. When the thread pool is in the shutdown or stop state, and all worker threads have been destroyed, the task cache queue has been emptied or the execution finishes, the thread pool is set to the TERMINATED state.
3. Blocking queue of Task cache

? If the arrival rate of a new request exceeds the processing rate of the thread pool, the newly arrived request is staged in the runnable wait queue workqueue of the thread pool management, and the Task force is listed as the Blockingqueue type of blocking queue.

? The blocking queue operation can be divided into the following:

Throw exception response Special-value response Blocking response Timeout response
Insert Add (o) Offer (o) put (o) Offer (o,timeout,timeunit)
Remove remove (o) poll (o) take (o) Poll (timeout,timeunit)
check element (o) Pee K (o)
    • Throw exception response: Throws an exception if the operation is not immediately satisfied.
    • Special Value response: Returns a special value, such as false or a null response, if the operation cannot be performed immediately.
    • Blocking response: If the operation cannot be performed immediately, it will block wait until the execution condition is met
    • Timeout response: If the operation cannot be performed immediately, wait for a certain amount of time to execute if the condition is met, otherwise return a value corresponding to whether the execution succeeds.

Blockingqueue Implementation class:

    1. Arrayblockingqueue : is a bounded queue, and the internal storage structure is an array. You need to specify the queue size when you start to use it, and you cannot modify the size during use.
    2. Linkedblockingqueue : The internal use of a linked list as a storage structure, you can specify the size as a bounded queue, if no size is specified, the default is the Integer.max_value size of the "unbounded" queue.
    3. Priorityblockingqueue : is an unbounded concurrent queue that sorts the elements in the queue according to a certain rule and sorts the threads in the thread pool according to their priority.
    4. synchronousqueue : Actually not a real queue, but a mechanism for handoff between threads. To put an element into the Synchronousqueue queue, another thread must be waiting for the element to be accepted. If there is no thread waiting, and the thread pool current size is less than the maximum value of the thread pool, Threadpoolexecutror creates a new thread to perform this task.
    5. Delayqueue : holds the element until a specific delay expires. The injected element must implement the Java.util.concurrent.Delayed interface.

How to block synchronization:

? Blocking queues implement blocking synchronization in a very simple way, using ReentranLock multiple conditions for blocking control, such as arrayblockingqueue Source:

//Constructors PublicArrayblockingqueue (intCapacity,BooleanFair) {if(Capacity <=0)Throw NewIllegalArgumentException (); This.Items=NewObject[capacity]; Lock =NewReentrantlock (fair);//NULL condition, Full conditionNotempty = lock.newcondition(); Notfull = lock.newcondition(); }//Insert Function Public void put(e)throwsinterruptedexception {Checknotnull(e);FinalReentrantlock lock = This.Lock;//interruptible lockLock.lockinterruptibly();Try{ while(count = = items.)length) Notfull.await();Enqueue(e); }finally{//UnlockLock.Unlock(); }    }

Selection policy for blocking queues:

? It is reasonable to set a line for the thread pool or work queue only when the tasks are independent of each other. If there is a dependency between the tasks, then a bounded thread pool or queue can cause a "hunger" deadlock problem. You can choose newCachedThreadPool .

4, four thread pool detailed

? The Java class Library provides a flexible thread pool and some configuration that can be Executors created by using the static factory method in:

    • Newfixedthreadpool

      • Brief introduction

? Newfixedthreadpool will create a thread pool of fixed length, whenever a task is committed, a thread is created, until the maximum number of thread pools is reached, and the size of the thread pool is no longer changing, if a thread should end in the middle of the exception exception, The thread pool will then make up one of the threads to join the thread pools.

   -Source ~~~java public static executorservice newfixedthreadpool (int nthreads) {return new Threadpoolexecutor (nTh Reads, Nthreads, 0L, Timeunit.milliseconds, new    Linkedblockingqueue<runnable> ()); } public static Executorservice newfixedthreadpool (int nthreads, threadfactory threadfactory) {return new T                                      Hreadpoolexecutor (Nthreads, Nthreads, 0L, Timeunit.milliseconds,    New Linkedblockingqueue<runnable> (), threadfactory);   }~~~?   As you can see, the core pool size of the newfixedthreadpool is consistent with the maximum size of the thread pool, meaning that the thread pool size is progressively created to the maximum value when the task is accepted. The thread's survival time is set to 0 milliseconds, stating that the thread pool of the core pool does not expire, so the number of threads in the core pool is created, unless the exception terminates, and does not stop automatically because of problems such as timeouts. See ' Allowcorethreadtimeout (Boolean) ' Source code: ~~~java public void Allowcorethreadtimeout (Boolean value) {//if Keepalivetim       E is 0 or less than 0, you cannot set the core pool auto death if (value && keepalivetime <= 0)     throw new IllegalArgumentException ("Core threads must has nonzero keep alive times");            if (value! = allowcorethreadtimeout) {allowcorethreadtimeout = value;        if (value) interruptidleworkers (); }    }~~~
  • Analysis

    ? Using unbounded linkedblockingqueue to block queues, if a task request is faster than the thread processing speed, can cause a large backlog of tasks to be processed in the blocking queue, consuming large amounts of memory, resulting in degraded performance or crashes.

  • Newcachedthreadpool

  • Brief introduction

    ? Newcachedthreadpool will create a cacheable thread pool that will reclaim idle threads if the current size of the thread pool exceeds the processing requirements, and when the demand increases, you can add new threads that have no limit on the size of the thread pool.

  • SOURCE Analysis

      Public StaticExecutorserviceNewcachedthreadpool() {return NewThreadpoolexecutor (0, Integer.Max_value, 60L, Timeunit.SECONDS,NewSynchronousqueue<runnable> ()); } Public StaticExecutorserviceNewcachedthreadpool(Threadfactory threadfactory) {return NewThreadpoolexecutor (0, Integer.Max_value, 60L, Timeunit.SECONDS,NewSynchronousqueue<runnable> (), threadfactory); }

    ? The core pool size is set to 0, and the maximum size of the thread pool is set to infinity, indicating that the thread pool is not in the core pool, that is, all threads in all thread pools will time out to die. The thread idle time is 60 seconds, which means that if the thread is idle for 60 seconds it will be killed. The blocking queue uses the Synchronousqueue queue, and the submitted tasks are not staged in the queue, but instead are transferred to the thread to execute directly.

  • Analysis

    ? It provides better queueing performance than a fixed-size thread pool, and if a task request is too frequent, causing the task to commit faster than the thread request, it may cause the application to create a large number of threads that can degrade performance or even crash. Therefore, if you limit the number of current tasks sufficient to meet the requirements of resource management, you prefer a bounded queue.

  • Newsinglethreadexecutor

  • Brief introduction

    ? Newsinglethreadexecutor is a single-threaded Executor that creates a single worker thread to perform a task, and if the thread ends abnormally, a new thread is created to replace it. Newsinglethreadexecutor ensures that tasks are executed serially (for example, Fifo,lifo, precedence, and so on) in the order in which they are queued.

  • SOURCE Analysis

       Public StaticExecutorserviceNewsinglethreadexecutor() {return NewFinalizabledelegatedexecutorservice (NewThreadpoolexecutor (1,1, 0L, Timeunit.MILLISECONDS,NewLinkedblockingqueue<runnable> ())); } Public StaticExecutorserviceNewsinglethreadexecutor(Threadfactory threadfactory) {return NewFinalizabledelegatedexecutorservice (NewThreadpoolexecutor (1,1, 0L, Timeunit.MILLISECONDS,NewLinkedblockingqueue<runnable> (), threadfactory)); }

    ? The maximum size of the core pool and the thread pool is 1, which means that the thread pool can hold only one thread and 0 milliseconds of survival, indicating that it does not automatically die. With borderless Linkedblockingqueue blocking queues, tasks that cannot be handled in a timely manner can accumulate indefinitely in the blocking queue, potentially causing a memory leak.

  • Newscheduledthreadpool

  • Brief introduction

    ? Newscheduledthreadpool creates a fixed-length thread pool and performs tasks in a deferred or timed manner, similar to Timmer.

  • SOURCE Analysis

     Public StaticScheduledexecutorserviceNewscheduledthreadpool(intCorepoolsize) {return NewScheduledthreadpoolexecutor (corepoolsize);} Public StaticScheduledexecutorserviceNewscheduledthreadpool(intCorepoolsize, Threadfactory threadfactory) {return NewScheduledthreadpoolexecutor (Corepoolsize, threadfactory);}//Use of Delayedworkqueue blocking queue PublicScheduledthreadpoolexecutor (intCorepoolsize, Threadfactory threadfactory) {Super(Corepoolsize, Integer.)Max_value,0, nanoseconds,New Delayedworkqueue(), threadfactory); }

    ? You can see that Newscheduledthreadpool returned a Scheduledexecutorservice object that was not the same as the previous three returned executorservice. The delayedworkqueue is used as a blocking queue and executed at timed intervals. Scheduledthreadpoolexecutor Method:

    // 延迟执行,只会执行一次    publicschedule(Runnable command,                                       long delay, TimeUnit unit);// 延期定时执行,重复执行多次publicscheduleAtFixedRate(Runnable command,                                                  long initialDelay,                                                  long period,                                                  TimeUnit unit);

    ?

Java multithreaded learning thread pool detailed

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.