Thread pool in Android

Keywords: Android

Thread pool in Android

I. Preface

There are many benefits to using thread pools. The advantages of thread pools can be summarized as follows:
1. Reuse threads in the thread pool to reduce the performance overhead of creating and destroying threads.
2. Effectively control the maximum number of concurrent threads in the thread pool, so as to avoid blockage caused by a large number of threads grabbing system resources.
3. It can manage threads simply, and provide regular execution and specified time interval circular execution.

II. ThreadPool Executor

The thread pool in Android is implemented as ThreadPool Executor, which provides a series of parameters to configure the thread pool. Its construction method is as follows:

public ThreadPoolExecutor(  
    int corePoolSize,   //Number of core threads
    int maximumPoolSize,   //Maximum number of threads
    long keepAliveTime, //Timeout duration                           
    TimeUnit unit,  //Specified time unit, enumeration type
    BlockingQueue<Runnable> workQueue,  //Task queue
    ThreadFactory threadFactory//Thread Factory Interface
    )  

Description of parameters:

  • corePoolSize Core ThreadTimeOut is set to true. When allowCoreThreadTimeOut is true, idle core threads will be idle when waiting for new tasks. The time is set by keepAliveTime, and the timeout will be terminated.
  • Maximum PoolSize maximizes the number of threads, and if the number of active threads exceeds it, subsequent tasks will be blocked.
  • Keeping AliveTime non-core threads run out of time and are recycled when exceeded. When allowCoreThreadTimeOut is true, it applies to core threads.
  • UnitkeepAliveTime unit s, enumeration type, commonly used TimeUnit. MILLISECONDS (ms), TimeUnit. SECONDS (s), TimeUnit. MINUTES (min), and so on.
  • The workQueue task queue, where the execute method of the thread pool stores the Runnable object.
  • The threadFactory thread factory has only one new Thread (Runnable) method to create new threads for the thread pool.

ThreadPoolExecutor performs task rules:
1. Number of threads < Number of core threads to start a core thread to perform tasks.
2. Number of threads >= Number of core threads, insert tasks into task queues and wait for execution (task queues are not full).
3. When the task queue is full, start a non-core thread to execute the task immediately.
4. The number of threads reaches the maximum specified by the thread pool, refuses to execute and throws exceptions.

Thread pool classification

According to different parameters, four types of thread pools with different functional characteristics are designed in Android, which are implemented directly or indirectly by setting ThreadPool Executor. They are Fixed ThreadPool, Cached ThreadPool, Scheduled ThreadPool and Single ThreadExecutor.

1. FixedThreadPool
Use:

public static ExecutorService newFixThreadPool(int nThreads){  
    return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());  
}  

Executors.newFixThreadPool(5).execute(r);  

Description: From the parameters, we can see that it only has core threads, fixed number, and will not recycle, there is no timeout limit. So, when all the core threads are full, the new task is in a waiting state until there are threads idle. These features enable FixedThreadPool to respond quickly to external requests.

2. CachedThreadPool
Use:

public static ExecutorService newCachedThreadPool(){  
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit. SECONDS, new SynchronousQueue<Runnable>());  
}  


Executors.newCachedThreadPool().execute(r);  

Note: There are no core threads in CachedThreadPool. The maximum number of threads is Integer.MAX_VALUE, which means there is no limit on the number of threads. So when all threads are active, new threads will be created for new tasks. Otherwise, idle threads (60s idle time, will be recycled after that, so there are probably 0 threads in the thread pool) will be used to process tasks. The task queue SynchronousQueue is equivalent to an empty set, and any task is executed immediately.

3.ScheduledThreadPool
Use:

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize){  
return new ScheduledThreadPoolExecutor(corePoolSize);  
}  
public ScheduledThreadPoolExecutor(int corePoolSize){  
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedQueue ());  
}  

//Execute r task after 2s
Executors. newScheduledThreadPool(5).scheduleAtFixedRate(r, 2000, TimeUnit.MILLISECONDS);  
//After delaying 10 ms, the r task is executed every 2 seconds
Executors. newScheduledThreadPool(5).scheduleAtFixedRate(r, 10, 2000, TimeUnit.MILLISECONDS);  

Note: The number of core threads is fixed, and there is no limit on the number of non-core threads (restrictions will be immediately recycled). Scheduled ThreadPool is mainly used to perform timing tasks and repetitive tasks with fixed periods.

4.SingleThreadExecutor
Use:

public static ExecutorService newSingleThreadPool (){  
    return new FinalizableDelegatedExecutorService ( new ThreadPoolExecutor (1, 1, 0, TimeUnit. MILLISECONDS, new LinkedBlockingQueue<Runnable>()) );  
}  


Executors.newSingleThreadPool ().execute(r);  

Description: This thread pool has only one core thread, and all tasks are completed sequentially in the same thread. So there is no need to deal with thread synchronization.

Posted by devman42 on Thu, 04 Apr 2019 14:09:29 -0700