Android asynctask Internal thread pool brief analysis of asynchronous execution task mechanism

Source: Internet
Author: User

The following is an analysis of the source code for API 25 Asynctask:

Using Asynctask if the Execute method is called to perform the task synchronously, you want to execute the task asynchronously and call the Executeonexecutor method directly, in most cases we will use the Asynctask internal static thread pool.

Thread_pool_executor, this is not to analyze the internal process of asynctask, but to simply introduce the workflow of the thread pool. You can see that the Thread_pool_executor is configured as follows:

New Threadpoolexecutor (Core_pool_size, Maximum_pool_size, Keep_alive_seconds, Timeunit.seconds, SPoolWorkQueue, Sthreadfactory);

Some parameters of Threadpoolexecutor are briefly introduced:

int Corepoolsize, the number of core threads, can be kept alive in the thread pool, unless allowcorethreadtimeout is set, which allows the core thread to time out. int maximumpoolsize, the maximum number of threads allowed in the thread pool. Long KeepAliveTime, when the number of threads in the thread pool exceeds the number of core threads, the non-core thread waits for KeepAliveTime time to terminate, that is, the time-out for non-core threads to wait for the task (survival time) is Keepalivetime,timeunit Unit, time-out units,blockingqueue<runnable> workQueue, buffer task queue, Threadfactory threadfactory used to create a new thread, you can set thread priority, and so on. You can view the API documentation or java.util.concurrent.ThreadPoolExecutor source code

Specifically, when a task is committed to the thread pool, it will look at whether the core thread has a task executing, if the core thread is idle, the core thread executes the task, otherwise the task is added to the buffer queue, and the task in the buffer queue is executed after the core thread finishes executing the task. If there are more tasks, the buffer queue is full, and there is a task commit, the non-core thread is started to perform the task, and if the number of non-core threads is all working, that is, the number of threads in the thread pool reaches the limit of the maximum number of threads maximum_pool_size. Submitting a task to the thread pool will report an exception that denies execution of the task Java.util.concurrent.RejectedExecutionException

You can use the following code to test it simply:

Customize a Asynctask First

  

static int index = 1;
Static class Myasynctask extends Asynctask<void, void, void> { @Override protected Void doinbackground ( Void ... params) { systemclock.sleep (+); return null; } @Override protected void OnPostExecute (void aVoid) { log.d (This.getclass (). Getsimplename (), "task#" + Index + "had executed."); index++; } }

Here, in order to be able to see the process described above, let the thread sleep in Doinbackground for 2 seconds, and perform a log for each asynctask output, with the index identifier is the number.

Then submit the task to the thread pool

        int cpu_count = Runtime.getruntime (). Availableprocessors ();        int core_pool_size = Math.max (2, Math.min (Cpu_count-1, 4));        int maximum_pool_size = Cpu_count * 2 + 1;        int taskmaxcounts =  maximum_pool_size +;        for (int i = 0; i < taskmaxcounts; i++) {            new Myasynctask (). Executeonexecutor (Asynctask.thread_pool_executor, (Vo ID) null);        }

The maximum number of tasks that can be accommodated at the same time is: Maximum_pool_size + 128 (number of buffer queue tasks), for API25 version, how the CPU is 4 core, then the maximum task number is 4 * 2 + 1 + 128 = 137.

When thread pool threads have tasks executing and the buffer queue is full, continuing to commit to the thread pool will report an exception, where you can change taskmaxcounts to Maximum_pool_size + 129.

Run the program again to see the Exception Log information

  

 FATAL exception:main Process:com.aquarius.test, pid:22425 java.lang.RuntimeException:Unable to start activity com Ponentinfo{com.aquarius.test/com.http.study.demo.volleyactivity}: Java.util.concurrent.RejectedExecutionException:Task [email protected] rejected from [email protected][ Running, pool size = 9, Active threads = 9, queued tasks = $, completed tasks = 0] at Android.app.ActivityThread.perfo Rmlaunchactivity (activitythread.java:2449) at Android.app.ActivityThread.handleLaunchActivity ( activitythread.java:2509) at android.app.activitythread.access$1000 (activitythread.java:153) at Android.app.activitythread$h.handlemessage (activitythread.java:1373) at Android.os.Handler.dispatchMessage ( handler.java:102) at Android.os.Looper.loop (looper.java:154) at Android.app.ActivityThread.main ( activitythread.java:5524) at Java.lang.reflect.Method.invoke (Native Method) at com.android.internal.os.zygoteinit$ Methodandargscaller.run (zygoteinit.java:740) at COM. Android.internal.os.ZygoteInit.main (zygoteinit.java:630) caused by: Java.util.concurrent.RejectedExecutionException:Task [email protected] rejected from [email protected][ Running, pool size = 9, Active threads = 9, queued tasks = $, completed tasks = 0] at java.util.concurrent. Threadpoolexecutor$abortpolicy.rejectedexecution (threadpoolexecutor.java:2014) at Java.util.concurrent.Thread Poolexecutor.reject (threadpoolexecutor.java:794) at Java.util.concurrent.ThreadPoolExecutor.execute (Threadpoo lexecutor.java:1340) at Android.os.AsyncTask.executeOnExecutor (asynctask.java:607)

  

Android asynctask Internal thread pool brief analysis of asynchronous execution task mechanism

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.