Android Development: Asynctask source code full parsing

Source: Internet
Author: User

In the Java development, has been exposed to a lot of open source code, I can understand the code but want to express it is a bit difficult, starting from today, gradually began to analyze some open source code and recorded as a blog to share, hoping to improve their ability to express, if there is anything wrong in the article, Readers are welcome to point out in the comments to facilitate my timely amendment, so as not to mislead other readers, if you have any better suggestions also welcome to leave your comments below, I am greatly honored. Please bring the friend who reproduced this articleLink to original:http://blog.csdn.net/d_clock/article/details/43805779All right, let's go.
As an Android developer, you must not be unfamiliar with asynctask, the asynchronous Operation class. It's the most controversial class I've ever had since I was a sophomore, and I've seen a lot of people on the Web Asynctask the performance of the groove, the concurrency is not enough, and so on, in the code of the open source framework I read, many asynchronous operations are basically not asynctask, Are using Java thread pool operations, so that for some time I also never use Asynctask, think asynctask a lot of shortcomings, later in the company of a great God said a "you did not find, Has the asynctask encapsulated the interaction between the asynchronous thread and the UI thread? Google provides this class out to developers to use nature has his reason ", I think carefully, the great God said also quite reasonable, think back to see the framework of the basic use of thread pool to do asynchronous operations, basically because these frameworks are not involved in the interaction with the UI, so you can completely directly use the thread pool to complete. So spend some time to ponder over the source code of the Asynctask (in fact, this code has been open many times, always see a new experience), and a piece of the content.
The use of Asynctask in daily development is like this demo code provided by the official documentation, first inheriting the Asynctask class to implement the corresponding generic parameters, and overriding the implementation of the Doinbackground abstract method, which is used to perform the asynchronous operations we need.

How to use Asynctask to do asynchronous operation, very simple, also a section of the official demo Code

Just need to new out of this asynctask and invoke execute to the corresponding parameters, that is, you can complete the corresponding asynchronous operation process, and finally return the results to OnPostExecute in the main thread in the process, the call is really very convenient to achieve and two threads of interaction. Here, we have re-asynctask the basic use of one side, if you are not familiar with the Android programmer, you should go to the toilet wall detention.Finally, let's add that some of the things to be aware of when using Asynctask programming:

    1. The Asynctask object must be created in the UI thread
    2. The Execute method must be called in the UI thread
    3. Do not directly call OnPreExecute (), OnPostExecute, Doinbackground in your program,
      Onprogressupdate method
    4. A Asynctask object can only be executed once, that is, the Execute method can be called only once, otherwise the run-time exception is reported
    5. Asynctask is not designed to handle time-consuming operations and takes a few seconds, and it is highly recommended that you use Executor,threadpoolexecutor and futuretask if you want to take a long time to operate.

The next step is to watch the Asynctask source code, the first to look at the constructor and some related variables

Cpu_count: The number of cores of the CPU
core_pool_size: Number of concurrent threads in the thread pool, directly linked to CPU cores
maximum_pool_size: Maximum number of threads in a thread pool, directly linked to CPU cores
keep_alive: Maximum time to live thread pool threads
sthreadfactory: The factory used to construct the thread pool, overriding the Newthread method to name each thread for easy debugging tracing
Spoolworkqueue: The work queue in the thread pool, chained blocking queue with a maximum capacity of 128
Thread_pool_executor: Multi-task concurrent worker thread pool, initialization parameter is above each big parameter
Serial_executor: The serial worker thread pool, the implementation class for the following Serialexecutor

Shandler: handler for thread interaction in the Asynctask class, implementing the class as an inner classInternalhandler(The implementation of Asynctask is to encapsulate the thread and the handler to achieve interaction, eliminating the process of becoming our own package)
Message_post_result: Shandler The message type of the returned result
message_post_progress: Shandler message type to return progress
Sdefaultexecutor: The default thread pool for the Asynctask class, which is initialized by default with Serial_executor serial thread pooling
Mworker: A class that implements the callable interface, which is initialized in the constructor.
mfuture: futuretask instance, used in conjunction with Mworker, is also initialized in the following constructor
Mstatus: Marks the current asynctask state of operation, with pending, RUNNING, finished three of the three states that are used to represent waiting, running, and running ends.
mcancelled: The mark bit to run the task is canceled
mtaskinvoked: The tag bit where the task has been scheduled to run

Here, we have a cursory look at some of the basic parts of the code, first understand the above to be able to understand the next to continue to watch the code flow, we know that to execute a asynctask, only after new out, call the Execute method to start an asynchronous task, The next step is to start with the execute code, which is shown in the official documentation, with two execute methods, which we usually call the red box below.

Next follow the code here, then the onlookers

You can see that the EXECUTE function calls the Executeonexecutor function and returns the result, and what Executeonexecutor actually does, from the name, is that it should be the thread pool that performs a task, There are two parameters that he passed in, except for the variable-length arguments passed in by the execute itself, which is the static variable sdefaultexecutor of the Asynctask class, a static thread pool that I have described earlier, by default a single-task serial thread pool, Now that we call Executeonexecutor, we'll be watching executeonexecutor inside the code.

From the implementation of this function, after entering this function, first start to judge the current execution of the state of the asynctask, if it is pendding, indicating that the current asynctask has never been executed, the Mstatus state is directly marked as running state, If Asynctask has executed the Execute method, the mstatus here will no longer be the pendding state will throw an exception directly, which can be well explained why a asynctask cannot invoke two execute

Because the pendding state has been set to another state at the time of the first call, the pendding state call in place is directly thrown illegalstateexception.
After setting the Mstatus state, the OnPreExecute method is then called,

This method is actually an empty method, because the invocation of the second side is still in the UI thread, so the subclass of Asynctask can override this method and implement some UI operations inside, this is the Asynctask design time left an extension method, Can be used to do some preparatory work before the asynchronous operation begins.

Immediately after that, the variable-length arguments passed in from execute are stored in the member variable of the Mworker, and the concurrent operation is performed using the default serial line pool

To this, the Executeonexecutor function of the basic completion of the following, continue to follow the exec code, and need to return to the Serialexecutor code and Asynctask in the constructor, Here's the opportunity to browse the implementation code for the Mworker class

As you can see, workerrunnable is actually an abstract static inner class with a MPARAMS member variable and inherits Callable,mworker is really an implementation instance of this class, as you can see in Executeonexecutor, The member variable Mparams in Mworker is used to store the arguments that we passed in when execute was called.

In the constructor, you can see that Mworker is instantiated and implements the call function in the callable interface (this function is the same as the run function in the thread pool executing the runnable interface, except that callable can return the result state). Entering the code in the Execute Call function, the first token that marks the current task's execution is set to true, then the execution priority of the thread is set, and it begins to enter the Doinbackground function we have been most common with, and pass in the parameters, There is a step-by-step understanding of the process of the call, after Doinbackground is executed, the execution results are returned as parameters to call the Postresult function, in the Postresult function you will see us more familiar handler, It returns the execution result in doinbackground to our UI thread's message queue, which is ultimately done by Handlemessage in handler to call the Finish method in Asynctask. And the finish method will eventually determine whether the doinbackground is normal execution, or midway is canceled, and ultimately to determine whether to call oncancelled or OnPostExecute, Finally, the execution state of Asynctask is set to finish to complete the interactive process between our entire asynchronous thread and the UI thread. Here's another place to be aware, is the done method in Mfeture, which is mostly used to handle the asynctask of execute.



It is important to note that the type of message sent out in Postresult is Message_post_result, and that the type of message is the case that Doinbackground is executed, but you can see the Internalhandler class above, In fact, there are two types of messages processed, both of which are also mentioned in the previous member variables, the other type of message is mainly used to update the UI thread to perform tasks in the asynchronous task, such as the update download progress we most often contact examples, Actually is in the Doinbackground method constantly to call the following publishprogress method, so you can also see very clearly, is actually using handler send the Message_post_progress type of message, Finally, the corresponding update operation is made in the Onprogressupdate method.


And the Onprogressupdate method you can see is actually also asynctask left us the way to extend the override

In this way, we have a basic understanding of the entire asynctask of the entire work process, and then we then look at the Asynctask to perform asynchronous concurrency. This time, before you look at the code, look at some of the things that Google has to offer in the API documentation interface.


Asynctask provides two types of thread pools, which have been introduced in the serial worker pool and the concurrency worker thread pool, and there are two functions executing Asynctask, one is execute, the other is Executeonexecutor, and the code above is seen, In fact, we call execute in the code also called the Executeonexecutor function, then you say these and Asynctask perform asynchronous task of the concurrency of the divine horse relationship? Let's go back to the code in Serialexecutor.

All of our asynctask of execute are ultimately packaged into a futuretask, then put into a executor to execute, and if we don't specify this executor separately, Then the default is to use Serialexecutor to perform these tasks, Serialexecutor internal through an array queue arraydeque to organize these executed tasks, from the code can be seen, each execution of a task, will be deleted in Arraydeque, You can only go on to the next task when you're done with the last runnable task, and if the previous task is not finished, then the task will never be executed, which explains why the previous asynctask is not suitable for a long-time task. Because once a task takes too long, the subsequent tasks will never be executed under the default Asynctask execution mechanism. If you look closely, you will see that the thread pool executing the asynctask is a static class variable, not a member variable, so if there is a very time-consuming task, it will involve all the asynctask in the app.
Google at the beginning of the design of the asynctask, mainly because the Android device configuration is still relatively poor, so not suitable for too many tasks concurrent execution, consider these reasons and asynctask into this serial execution, but with the development of hardware, Google also takes into account the multitasking concurrency problems faced by asynctask, so the Android3.0 also expands the additional thread_pool_executor concurrent thread pool, but from the initialization Thread_pool_ Executor's parameters, Google still controls the number of Asynctask simultaneous tasks, and directly linked to the CPU's number of cores, this is to a certain extent considered the performance of the problem, ANDROID3.0 expands the Executeonexecutor interface and even defines its own concurrent thread pool from the asynctask outside of the Executeonexecutor interface. To this I asynctask of the source code parsing has almost come to an end, and finally want to talk about some of the main is the Asynctask execution state, as well as cancel the execution of Asynctask, about these can see the following several pieces of code



Presumably, we are already familiar with the basic operations of the entire asynctask and the associated execution processes.
Finally, I would like to make a personal wordy summary, from my own current development experience, asynctask This class really has done a good package, has been the asynchronous thread and UI thread interaction between the very good processing, so developers can from the Google offers the class happily programmed , if you consider the problem of the number of concurrent tasks, You can also use the interface provided after 3.0 to increase the number of concurrent operations, but we still need to control the maximum concurrency of the task, because the number is too large can also cause the performance of the app, which is why Google provides a multi-task thread pool concurrent task number to be directly linked to the CPU core number of reasons, and trace back to Asyncta SK's essence, we from the source code can also be seen at a glance, it is actually futuretask and handler of the combination of the body.
About Asynctask Source code resolution to this end, I hope this article can help you in the Android development to better understand and use the Asynctask,in order to better help everyone clear ideas, follow-up I will write another blog with a UML diagram to express the asynctask work process, it will appear more intuitive。respect the original, reproduced please indicate the source:http://blog.csdn.net/d_clock/article/details/43805779

Android Development: Asynctask source code full parsing

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.