Android performance optimization thread pool policy and knowledge of the thread pool

Source: Internet
Author: User

the mechanism of thread operation
    • 1. Too many threads will consume CPU
    • 2. Single-core CPUs, only one thread at a time, multi-core CPUs can handle multiple threads at the same time
    • 3. The operating system for each running thread to schedule a certain amount of CPU time----' time slice ', the system through a circular way for the thread to provide a time slice, the thread in its own time to run, because the time is quite short, multiple threads frequently switch, so the user feels like multiple threads running at the same time, But if the computer has multiple CPUs, the thread can actually run at the same time.

the role of the thread pool
    • 1. The thread pool is a technique for pre-creating threads. The thread pool creates a certain number of threads, puts them in an idle queue, and then re-uses the resources before the task arrives. `
    • 2. Reduce the frequent creation and destruction of objects. `
    • 3. frequent creation and destruction of thread consumption resources, time consuming
    • 4. because some threads take longer to execute than to create and destroy a thread '

classes involved in the thread pool
    • * Executor:java the top interface of the thread pool inside
    • * Executorservice: TRUE thread pool interface
    • * Scheduledexecutorservice: Can be similar to timer/timertask, solve the problem that need to repeat the task
    • * Threadpoolexecutor (FOCUS): The default implementation of Executorservice.
    • * Scheduledthreadpoolexecutor: Inherit Threadpoolexecutor's Scheduledexecutorservice interface implementation, periodic task scheduling class implementation.


Executors
> executors:jdk1.5 A new class that provides a number of static factories, generating some common thread pools,Threadpoolexecutor is the underlying implementation of the Executors class

There are 4 ways to create a thread pool:
    • 1.newSingleThreadExecutor
Creates a single threaded pool of threads. This thread pool has only one thread at work, which is equivalent to single-threaded serial execution > All tasks. If this only thread is due to an abnormal knotBundle, a new thread will replace it. This thread pool > ensures that the order in which all tasks are executed is performed in the order in which the tasks are submitted.
    • 2.newFixedThreadPool
Creates a fixed-size thread pool. Each time a task is committed, a thread is created until the thread reaches the maximum size of the threads pool. Once the size of the thread pool reaches its maximum value, it will remainChange, if a thread ends up performing an exception, the threads pool complements a new thread.
    • 3.newCachedThreadPool
Creates a cacheable pool of threads. If the size of the thread pool exceeds the thread that is required to process the task,Then a partially idle (60 second non-performing) thread is reclaimed, and when the number of tasks increases, the thread pool can intelligently add new threads to handle the task. This thread pool does notPool size is limited, and the thread pool size depends entirely on the maximum thread size that the operating system (or JVM) can create.
    • 4.newScheduledThreadPool
Create a thread pool of unlimited size. This thread pool supports the need to schedule and periodically perform tasks.

threadpoolexecutor Introduction:
Construction method Public Threadpoolexecutor (int corepoolsize,//core pool size int maximumpoolsize,//thread pool maximum thread count)                               Long keepalivetime,//hold time timeunit unit,//time unit blockingqueue<runnable> workqueue,//task Queue threadfactory threadfactory,//thread Factory Rejectedexecutionhandler handler)//Abnormal traps
Construction-Related parameter interpretation
*corepoolsize: 'size of the core pool', this parameter is very much related to the implementation principle of the thread pool described later. After the thread pool has been created, by default, there are no threads in the thread pools, instead of waiting for a task to be created to perform the task, unless the prestartallcorethreads () or Prestartcorethread () method is called. As you can see from the names of these 2 methods, the meaning of the pre-created thread is to create a corepoolsize thread or a thread before the task arrives. By default, after a thread pool has been created, the number of threads in the thread pools is 0, and when a task comes, a thread is created to perform the task, and when the number of threads in the thread pool reaches corepoolsize, the incoming task is placed in the cache queue;
*maximumpoolsize: 'thread pool Maximum number of threads', this parameter is also a very important parameter, which represents the maximum number of threads that can be created in a thread pool;
*KeepAliveTime: ' Indicates how long the thread will stay when no task is executed. ' By default, KeepAliveTime only works if the number of threads in the thread pool is greater than corepoolsize, until the number of threads in the thread pool is not greater than corepoolsize, that is, when the number of threads in the thread pool is greater than corepoolsize. If a thread is idle for KeepAliveTime, it terminates until the number of threads in the thread pool does not exceed corepoolsize. However, if the Allowcorethreadtimeout (Boolean) method is called, the KeepAliveTime parameter also works when the number of threads in the thread pool is not greater than corepoolsize, until the number of threads in the thread pool is 0;
*Unit: Parameter KeepAliveTime 'Time Unit', there are 7 kinds of values
Timeunit.days;             Days Timeunit.hours;           Hour timeunit.minutes;           Minutes Timeunit.seconds;      Seconds timeunit.milliseconds;      Ms Timeunit.microseconds;       Subtle timeunit.nanoseconds; Na-Sec
*WorkQueue: 'Task Queue', is a blocking queue that is used to store the tasks awaiting execution, and the choice of this parameter is also important, which can have a significant impact on the running process of the thread pool.
If the blockingqueue is empty, the operation from the Blockingqueue will be blocked into the waiting state until the blockingqueue into the object will be awakened, similarly, if the blockingqueue is full, Any attempt to store something inside will also be blocked into a wait state until the blockingqueue has space to be woken up to continue operation.
1. Introduction to the Basic API * __ Adding elements to the queue __ * Add (E): Non-blocking method, add element to Blockingqueue, if Blockingqueue can accommodate, return true, otherwise throw an exception.  * Offer (E): Non-blocking, indicates that the element is added to the blockingqueue if possible, that is, true if the blockingqueue can be accommodated, otherwise false is returned. * __put (E) __: Blocking method, adding elements to Blockingqueue, if Blockingqueue no space, then the thread calling this method is blocked until there is room in blockingqueue to continue.
* __ The method of fetching elements from the queue __ * __poll (TIME) __: Blocking method, take the first element in the Blockingqueue, if not immediately remove, you can wait for the times specified by the date parameter, not to return null. * __take () __: Take the Blockingqueue in the first place of the object, if the blockingqueue is empty, blocking into the waiting state until a new object is added to the blockingqueue.
2. Subclass Introduction * ' Arrayblockingqueue (bounded queue) ': FIFO queue, specified size of Blockingqueue, its constructor must take an int parameter to indicate its size
* ' Linkedblockingqueue (unbounded queue) ': FIFO queue, Variable size blockingqueue, if its constructor with a specified size parameter, the resulting blockingqueue has a size limit, if not with the size parameter, The size of the generated blockingqueue is determined by Integer.max_value.
* ' Priorityblockingqueue ': Priority queue, similar to Linkedblockingqueue, but the elements in the queue are not FIFO, depending on the natural sort order of the objects or the order of comparator determined by the constructors
* ' Synchronousqueue (direct Commit policy) ': Alternate queue, the operation must be in the queue first put in, then take out, alternately to deal with the addition and removal of elements

*threadfactory: `Thread Factory' How to create a thread
*Handler: Task queue Add 'Abnormal Traps', refer to Rejectedexecutionhandler
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 (repeat this process) Threadpoolexecutor.callerrunspolicy: The task is handled by the calling thread

Introduction to the underlying API
* IsShutDown (): Determines whether the thread pool is closed * isterminated (): Determines whether the task in the threads sink is completed * shutdown (): No longer receives new tasks after invocation, if there is a task inside, executes * shutdownnow (): No longer accepted after the call New task, if there is a wait task, move out of the queue; * Submit (): Commit to execute Task * EXECUTE (): Perform task

processing strategy After the task is submitted to the thread pool
1. If the number of threads in the current thread pool is less than corepoolsize, each task will be created to perform this task; 2. If the number of threads in the current thread pool is >=corepoolsize, each task will attempt to add it to the task cache queue by 1. If added successfully, the task waits for the idle thread to remove it to execute;! [] (Img/task2.png) 2. If the add fails (typically the task cache queue is full), an attempt is made to create a new thread to perform the task; 3. If the number of threads in the current thread pool reaches maximumpoolsize, a task rejection policy is taken to handle it; 4. If the number of threads in the thread pool is greater than corepoolsize, if a thread is idle for more than KeepAliveTime, the thread is terminated until the number of threads in the thread pool is not greater than corepoolsize, and if the threads in the core pool are allowed to set the time to live, If the thread in the core pool is idle longer than KeepAliveTime, the thread is terminated.

processing strategy After the task is submitted to the thread pool metaphor
> If there is a factory, there are ten (' corepoolsize ') workers in the factory, each worker can only do one task at a time.
> so as long as there are 10 workers who are idle, ' The task is assigned ' to the idle worker;
> When 10 workers have a task to do, if the task is still in place, the task is queued (' Task queue ');
> If the number of new tasks is growing much faster than the speed at which workers do their jobs, then the factory supervisor may want to remedy such things as re-recruiting 4 temporary workers (' Create a new thread ') and assigning the task to the 4 temporary workers;
> If the 14 workers do not have enough speed to do their job, then the factory supervisor may want to consider no longer accepting new tasks or abandoning some of the previous tasks (' refuse to execute ').
> When one of the 14 workers is free and idle for more than a certain amount of time (' Idle Time '), the new task grows at a slower pace, and the factory supervisor may consider quitting 4 temporary workers, keeping the original 10, after all, to ask for extra workers to spend money.

--------------------------------------------------------------------------------------------------------------- -------------------------------------
Several recent discoveries of misuse of threadpoolexecutor have been found to be due to the lack of careful review of annotations and the internal workings of the mechanism, and the assumption of assumptions about parameters that lead to the creation of a new Threadpoolexecutor build parameter:

Public threadpoolexecutor (int corepoolsize,                            int maximumpoolsize,                            long KeepAliveTime,                            timeunit Unit,                            blockingqueue<runnable> WorkQueue,                            Threadfactory threadfactory,                            Rejectedexecutionhandler handler)  

See this parameter is easy to let people think is the line constructor keep Corepoolsize thread, if not enough, add thread into the pool until maximumpoolsize size, if not enough to workqueue Riga, If Workqueue is not enough to use Rejectedexecutionhandler to do refuse processing.

But this is not the case, the specific process is as follows:

1) Create a new thread when the pool size is less than corepoolsize and process the request

2) When the pool size equals corepoolsize, put the request into the workqueue, the free thread in the pool goes from the Workqueue to take the task and handle

3) When the Workqueue does not fit into the new task, the new thread sinks into the pool and processes the request, and if the pool size is up to maximumpoolsize, use Rejectedexecutionhandler to reject it.

4) In addition, when the number of threads in the pool is greater than corepoolsize, the extra thread waits for KeepAliveTime for a long time and destroys itself if no request can be processed.

The internal structure is as follows:


It can be found that Threadpoolexecutor relies on the blockingqueue blocking mechanism to maintain the thread pool, which is blocked by Workqueue.take () when there is nothing to do in the pool.

In fact, we can learn how to construct some special threadpoolexecutor through executes.

public static Executorservice newfixedthreadpool (int nthreads) {      return new Threadpoolexecutor (Nthreads, Nthreads,                                    0L, Timeunit.milliseconds,                                    new linkedblockingqueue<runnable> ());  }  
Newfixedthreadpool is a fixed-size threadpool.
public static Executorservice Newcachedthreadpool () {      return new Threadpoolexecutor (0, Integer.max_value,                                    60L , Timeunit.seconds,                                    new synchronousqueue<runnable> ());  }  

Newcachedthreadpool is more suitable for small tasks that do not have a fixed size and can be done quickly, and there is no need to maintain a pool, which is better than the direct new thread to be able to reuse the created thread within 60 seconds.

Other types of threadpool take a look at the build parameters and then combine the features described above to know its characteristics.


Thread Pool Tool class:
threadpoolfactory thread pool factory class threadpoolproxy thread pool proxy class
Threadpoolutils thread Pool tool class

threadpoolfactory:
public class Threadpoolfactory {public    static threadpoolproxy Normalthreadpool;    public static final int normal_corepoolsize = 5;    public static final int normal_maximumpoolsize = 5;    public static final Long normal_keepalivetime =;    public static Threadpoolproxy Getnormalthreadpool () {        //double detection mechanism        if (Normalthreadpool = = null) {            Synchronized (threadpoolfactory.class) {                if (Normalthreadpool = = null) {                    Normalthreadpool = new Threadpoolproxy (Normal_corepoolsize,
<span style= "White-space:pre" ></span>normal_maximumpoolsize,
<span style= "White-space:pre" ></span>normal_keepalivetime);        }} return normalthreadpool;}    }

Threadpoolproxy:
public class Threadpoolproxy {Threadpoolexecutor executor;    int corepoolsize;    int maximumpoolsize;    Long KeepAliveTime; Public threadpoolproxy (int corepoolsize, int maximumpoolsize, long keepalivetime) {this.corepoolsize = Corepoolsiz        E        This.maximumpoolsize = maximumpoolsize;    This.keepalivetime = KeepAliveTime; } public void Initthreadpoolproxy () {//double detection mechanism if (executor = = null) {synchronized (Threadpoo  Lexecutor.class) {if (executor = = null) {blockingqueue<runnable> workQueue = new                    Linkedblockingdeque<> ();                    Threadfactory threadfactory = Executors.defaultthreadfactory ();                    Rejectedexecutionhandler handler = new Threadpoolexecutor.abortpolicy (); Executor = new Threadpoolexecutor (corepoolsize, Maximumpoolsize, KeepAliveTime, Timeunit.seconds, WorkQueue,                Threadfactory, Handler); }            }        }    }   public void Exector (Runnable Runnable) {initthreadpoolproxy ();    Executor.execute (runnable);        } public void Remove (Runnable Runnable) {initthreadpoolproxy ();    Executor.remove (runnable); }}

threadpoolutils:
public class Threadpoolutils {    //execute    static Handler in UI Handler = new Handler ();    public static void Runtaskonmainthread (Runnable Runnable) {        handler.post (Runnable);    }    Non-UI execution public    static void Runtaskonthread (Runnable Runnable) {        threadpoolfactory.getnormalthreadpool (). Exector (runnable);    }}

It's here today. Thank you.



Android performance optimization thread pool policy and knowledge of the thread pool

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.