The thread pool in Java

Source: Internet
Author: User
Tags sorts

Overview

Multithreading is often used in our development. For example, in Android, because of the many limitations of the main thread, some time-consuming operations, such as network requests, we must run in a child thread. We tend to use the new thread to open a child thread, which is then switched to the main thread by handler after the child-thread operation is complete. So far we have been unable to manage the sub-threads we have created, and have unrestricted creation of sub-threads that compete with each other and are likely to crash or oom due to excessive resource usage. So in Java we have a thread pool to manage the threads we create.

use of the thread pool benefits of using the thread pool

Here we start with the benefits of using a thread pool.
1. Reuse threads that already exist in the thread pool, reducing the performance overhead caused by the creation and extinction of threads.
2. Can effectively control the maximum number of concurrent threads, improve the utilization of system resources, and also can avoid a large number of threads because of each other to preempt system resources and lead to congestion.
3. Be able to simple management of threads, and provide the functions of timing execution, periodic execution, single thread, concurrency control, etc.

Threadpoolexecutor

We can create a thread pool through threadpoolexecutor. Let's look at a construction method in Threadpoolexecutor.

publicThreadPoolExecutor(int corePoolSize,                          int maximumPoolSize,                          long keepAliveTime,                          TimeUnit unit,                          BlockingQueue<Runnable> workQueue,                          ThreadFactory threadFactory,                          RejectedExecutionHandler handler)
threadpoolexecutor parameter meaning

1. Corepoolsize
The number of core threads in the thread pool, by default, the core threads are surviving the thread pool, even if they are idle in their threads pool. Unless we set Threadpoolexecutor's Allowcorethreadtimeout property to True, this time the idle core thread waits for a new task to arrive with a time-out policy that is specified by KeepAliveTime. Once the time-out is exceeded, the idle core thread is terminated.
2. The maximum number of threads accommodated in the Maximumpoolsize
thread pool, and if the active thread reaches this value, subsequent new tasks will be blocked.
3. KeepAliveTime
Timeout when non-core threads are idle, and for non-core threads, the non-core thread is recycled when the idle time exceeds this time. This timeout is only effective on the core thread when the Allowcorethreadtimeout property of Threadpoolexecutor is set to true.
4. Unit
Specifies the unit of time for the KeepAliveTime parameter. He is an enumeration that can be used in units that have days (timeunit.days), Hours (timeunit.hours), minutes (timeunit.minutes), milliseconds (timeunit.milliseconds), microseconds ( Timeunit.microseconds, 1 per thousand ms) and Nanosecond (timeunit.nanoseconds, 1 per thousand μs); The
5. WorkQueue
Thread pool holds a blocking queue for tasks that are waiting to be executed. Runable objects that are committed through the Execute method in the thread pool are stored in the queue. We can select several blocking queues below.

    • Arrayblockingqueue: An array-based bounded blocking queue that sorts the elements in the queue according to FIFO (first-in-one-out) principles.
    • Linkedblockingqueue: A blocking queue that is based on a linked list, which sorts the elements in the queue according to the FIFO (first-in-a-out) principle.
    • Synchronousqueue: There is no capacity in the internal blocking queue. There is no cache space inside of it. Data elements in Synchronousqueue are only possible when we try to take them away.
    • Priorityblockingqueue: An infinite blocking queue with a priority.
    • We can also customize the blocking queue we need by implementing the Blockingqueue interface.

6. Threadfactory
A thread factory that provides the creation of a new thread for the thread pool. Threadfactory is an interface in which there is only one Newthread method.
7. Handler
He is a Rejectedexecutionhandler object, and Rejectedexecutionhandler is an interface with only one rejectedexecution method. Threadpoolexecutor calls the Rejectedexecution method in Rejectedexecutionhandler when the task queue is full and the active thread in the thread pool has reached the maximum value that is qualified or the task cannot be successfully executed. In Threadpoolexecutor, there are four internal classes that implement the Rejectedexecutionhandler interface. In the thread pool, it defaults to AbortPolicy, which throws a Rejectedexecutionexception exception when a new task cannot be processed. The following are the four optional values available in Threadpoolexecutor.

    • Callerrunspolicy: Runs the task only with the caller's thread.
    • AbortPolicy: Throws the rejectedexecutionexception exception directly.
    • Discardpolicy: Discard the task and do not process
    • Discardoldestpolicy: Discards the most recent task in the queue and executes the current task.
    • We can also customize our own handler by implementing the Rejectedexecutionhandler interface. Tasks such as logging or persistence that cannot be processed.
Threadpoolexecutor Execution Rules
    1. If the number of threads in the thread pool does not reach the core number of threads, it is time to start a core thread to perform the task.
    2. If the number of threads in the thread pool has exceeded the number of core threads, the task is inserted into the task queue and queued for execution.
    3. The task cannot be inserted into the task queue because the task queue is full. At this point, if the number of threads in the thread pool does not reach the maximum value set by the thread pools, a non-core thread is immediately launched to perform the task.
    4. If the number of threads in the thread pool reaches the maximum value specified, then the task is rejected, and the Rejectedexecution method in Rejectedexecutionhandler is called to notify the caller.
Use of Threadpoolexecutor

With all that said, let's take a look at how to use this threadpoolexecutor. First we create a thread pool through threadpoolexecutor.

new ThreadPoolExecutor(5,10,10,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<>());

There are several construction methods for Threadpoolexecutor, with default values for the other parameters in the construction method above. Once we've created a thread pool, here's a look at how to submit a task to the thread pool. We can submit a task to the thread pool through execute and submit two ways.
Execute
When we use execute to submit a task, because the Execute method does not return a value, we cannot determine whether the task was successfully executed by the thread pool.

executorService.execute(new Runnable() {    @Override    publicvoidrun() {        // doSomething    }});

Submit
When we use submit to submit a task, it returns a future where we can determine whether the task is successful or not, and get the return value through the Get method of the future. The Get method blocks until the task is complete, and the get (long timeout, Timeunit unit) method blocks for a period of time, and it is possible that the task is not finished.

Future<Object> future = executorService.submit(new Callable<Object>() {    @Override    publiccall() throws Exception {        // TODO Auto-generated method stub        returnnull;    }});try {    object = future.getcatch (InterruptedException e) {    // 处理中断异常    catch (ExecutionException e) {    // 处理无法执行异常    e.printStackTrace();}
Close the thread pool

We can close the thread pool by shutdown method or Shutdownnow method. For both of these ways of shutting down the thread pool, they all pass through all the threads in the threads pools, then call the thread's interrupt method in turn to break threads. Of course, there are some differences between the two methods of shutting down the thread pool (see note below for specific differences).
The IsShutDown method returns True when we call any of the following close methods. The Isterminaed method returns True when the thread pool is closed successfully. For tasks that are being performed in the thread pool if we want them to shut down the thread pool after completion, call the Shutdown method, and we want the Shutdownnow method to be called when the thread pool is closed Cheng the task being executed.

/*** 首先将线程池的状态设置成SHUTDOWN状态,然后中断所* 有没有正在执行任务的线程。*/executorService.shutdown();/*** 首先将线程池的状态设置为STOP,然后开始尝试停止所有的正在* 工作或暂停任务的线程*/executorService.shutdownNow();
java thread pool thread pool classification in Java

Here we introduce four kinds of thread pools in Java that are common to different functions. They are all directly or indirectly configured Threadpoolexecutor to achieve their respective functions. These four thread pools are newfixedthreadpool,newcachedthreadpool,newscheduledthreadpool and newsinglethreadexecutor respectively. These four thread pools can be obtained through the Executors class. These four thread pools are described below.
1. Newfixedthreadpool
We can create it through the Newfixedthreadpool method in executors, which is a thread pool with a fixed number of threads. The maximum number of threads that are accommodated in this thread pool is the number of core threads we set. If threads in the thread pool are idle, they are not recycled unless the thread pool is closed. If all the threads are active, the new task is back in the waiting state until the thread is idle. Because Newfixedthreadpool has only core threads and these threads are not recycled, it can respond more quickly to external requests. As can be seen from the implementation of the Newfixedthreadpool method below, Newfixedthreadpool has only core threads, and there is no time-out mechanism, with linkedblockingqueue, so there is no limit to the size of the task queue.

public   Static  executorservice newfixedthreadpool  (int  nthreads) {return  new  Threadpoolexecutor (Nthreads, nthreads, 0  L, Timeunit.mill Iseconds, new  linkedblockingqueue<runnable> ());} 

2. Newcachedthreadpool
We can create it through the Newcachedthreadpool method in executors, By following the Newcachedthreadpoolfan ' F here we can see that it has a core thread number of 0, and the thread pool has an integer maximum number of threads. Max_value. The Integer.max_value is a large number, and it is almost possible to say that the maximum number of threads in this thread pool can be arbitrarily large. The thread pool creates a new thread to handle the task when the threads in the thread pools are active. The line blocks until those in the thread pool is always 60 seconds long, so it is recycled when the thread is idle for more than 60 seconds. This means that if the entire thread pool's threads are idle for more than 60 seconds, there are no threads in the newcachedthreadpool thread pools, so it hardly consumes any system resources at this time. For newcachedthreadpool his task queue is synchronousqueue, which says there are no capacity blocking queues within Synchronousqueue. Synchronousqueue internal equivalent to an empty collection, we cannot insert a task into synchronousqueue. So, in the thread pool, if an existing thread is unable to receive the task, a new thread is created to perform the task.

publicstaticnewCachedThreadPool() {    returnnew ThreadPoolExecutor(0, Integer.MAX_VALUE,                                  60L, TimeUnit.SECONDS,                                  new SynchronousQueue<Runnable>());}

3. Newscheduledthreadpool
We can create it through the Newscheduledthreadpool method in executors, which has a fixed number of core threads, is almost unlimited for non-core threads, and is immediately recycled when non-core threads are in a restricted state.

public   Static  scheduledexecutorservice newscheduledthreadpool  ( int  corepoolsize) {return  new  scheduledthreadpoolexecutor (corepoolsize);} public  scheduledthreadpoolexecutor  (int  corepoolsize) {super  (Corepoolsize, Integer.max_value, 0 , nanoseconds, new  delayedworkqueue ());}  

4. Newsinglethreadexecutor
We can create it through the Newsinglethreadexecutor method in executors, where there is only one core thread in the pool, and there is no size limit for the task queue, which means that the task is active. Other tasks are queued in the task queue to be executed sequentially. Newsinglethreadexecutor unifies all external tasks into one thread, so we don't need to deal with thread synchronization between this task execution.

publicstaticnewSingleThreadExecutor() {    returnnew FinalizableDelegatedExecutorService        (new ThreadPoolExecutor(11,                                0L, TimeUnit.MILLISECONDS,                                new LinkedBlockingQueue<Runnable>()));}
four types of thread pool usage

Let's take a look at how these four thread pools are used.

Runnable command = new Runnable () {public void run () {//dosomething}};Executorservice Fixedthreadpool = Executors. Newfixedthreadpool(Ten);Fixedthreadpool. Execute(command);Executorservice cachedthreadpool= Executors. Newcachedthreadpool();Cachedthreadpool. Equals(command);Scheduledexecutorservice Scheduledthreadpool = Executors. Newscheduledthreadpool(Ten);// +Execute Coommandscheduledthreadpool after milliseconds. Schedule(Command, +, Timeunit. MILLISECONDS);Delay5milliseconds, each interval -Millisecond execution once Commandscheduledthreadpool. Scheduleatfixedrate(Command,5, -, Timeunit. MILLISECONDS);Executorservice Singlethreadexecutor = Executors. Newsinglethreadexecutor();Singlethreadexecutor. Execute(command);
Summary

The thread pool concept in Java also applies to Android, for example, when we develop an app, we can create a thread pool to handle all the sub-threading tasks to the thread pool, so we can manage to maintain our child threads through this thread pool. Reduces the overhead of the application.

The thread pool in Java

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.