To undertake the previous article, today we discuss the thread management of the concurrent network. It is well known that high concurrent multi-threaded network requests are common in network requests, and we cannot affect other network requests because of the previous network congestion, but too many threads deplete the limited CPU resources on the mobile side. How to deal with multiple concurrent operations, the network framework of each family is somewhat different, today we will look at how to choose.
Queue Selection Scheme
Network requests are generally implemented in a FIFO manner, so the queue to store the request task is most appropriate, in Java more commonly used queues have the following
1.ArrayBlockingQueue
2.LinkedBlockingQueue
3.PriorityBlockingQueue
Let us first to popularize the following Blockingqueue features
Blockingqueue
In a multithreaded environment, data sharing can easily be achieved through queues, such as the classic "producer" and "consumer" models, where data sharing between the two can be conveniently achieved through queues. Let's say we have a number of producer threads, and another number of consumer threads. If the producer thread needs to share the prepared data to the consumer thread and use the queue to pass the data, it is easy to solve the data sharing problem between them. But what if the producer and consumer are in a certain time period, in case the data processing speed does not match? Ideally, if the producer produces data at a faster rate than the consumer, and when the resulting data accumulates to a certain extent, then the producer must pause (block the producer thread) to wait for the consumer thread to finish processing the accumulated data, and vice versa. However, before the concurrent package was released, in a multithreaded environment, each of our programmers had to take control of these details, especially in the context of efficiency and thread safety, which would bring a great degree of complexity to our programs. Fortunately at this time, the powerful concurrent package turned out, and he also brought us a strong blockingqueue. (In the Multithreaded realm: so-called blocking, in some cases hangs a thread (that is, blocked), and once the condition is met, the suspended thread is automatically awakened)
Then let's take a look at the three common implementations of this subclass
-
Arrayblockingqueue
Array-based blocking queue implementation, within Arrayblockingqueue, maintains a fixed-length array to cache data objects in the queue. Arrayblockingqueue the same lock object when the producer puts the data and the consumer gets the data, which means they can't really run in parallel.
-
Linkedblockingqueue
is based on a linked list of blocking queues, similar to Arraylistblockingqueue, the default is the maximum value without specifying a length, so If the producer's speed is greater than the consumer's speed, perhaps not until the queue is full of congestion, the system memory may have been exhausted. While Linkedblockingqueue is able to efficiently handle concurrency data, it also uses separate locks for both producer and consumer to control data synchronization, which means that producers and consumers can operate the data in the queue in parallel with high concurrency, This improves the concurrency performance of the entire queue.
-
Priorityblockingqueue
Priority-based blocking queue (priority judgment is determined by the Compator object passed into the constructor), However, it is important to note that Priorityblockingqueue does not block data producers, but only the consumers who block the data when there is no data to consume. It is therefore important to pay particular attention to the fact that the producer produces data at a speed that is not faster than the consumer's consumption of data, or that it will eventually deplete all available heap memory space for a long time. When implementing Priorityblockingqueue, the internal control thread synchronizes the lock with a fair lock.
As can be seen, the traditional queue is a thread-blocking queue, which means that when we are on the network side of the producer or consumer imbalance, it is very easy to generate thread blocking. For example, if the user in a short period of time to do a large number of network operations, the consumer side of the execution speed will be far greater than the speed of the producer, if the use of arrayblockingqueue, execution efficiency will be stuck in the synchronous lock pull () and take () operation, Such thread blocking is not acceptable. The advantages of linkedblockingqueue at this time are far from being shown, and the choice of separating locks in the queue for the same element allows linkedblockingqueue to efficiently process concurrent data.
And the use of the priority queue is reflected in another scenario, assuming that the user has entered a main page to obtain dynamic data, while the background to submit updates to the user state of the operation, then if the update status is blocked, the user's main interface data will be slow to refresh, so the user experience will become very poor. Therefore, the combination of Priorityblockingqueue and Linkedblockingqueue is the perfect solution for the queue selection of network requests, taking into account the concurrency efficiency and the priority of the network request on the mobile side.
Multi-threaded selection scheme
Performance optimization is a bottleneck in resource-constrained mobile. When it comes to multithreading concurrency, the first time you think about it must be a thread pool. Using the thread pool can reduce the time spent on creating and destroying threads and the overhead of system resources. A fixed number of thread pools can effectively prevent memory resources from being exhausted and gain more resources for the UI thread. In the Android source code, already has the best practice template, I also not here more to repeat, on the asyncktask source!
Private Static FinalString Log_tag ="Asynctask";Private Static Final intCpu_count = Runtime.getruntime (). Availableprocessors ();Private Static Final intCore_pool_size = Cpu_count +1;Private Static Final intMaximum_pool_size = Cpu_count *2+1;Private Static Final intKeep_alive =1;Private Static FinalThreadfactory sthreadfactory =NewThreadfactory () {Private FinalAtomicinteger MCount =NewAtomicinteger (1); PublicThreadNewthread(Runnable R) {return NewThread (R,"Asynctask #"+ mcount.getandincrement ()); } };Private Static FinalBlockingqueue<runnable> Spoolworkqueue =NewLinkedblockingqueue<runnable> ( -);/** * A {@link Executor} that can is used to the execute tasks in parallel. */ Public Static FinalExecutor Thread_pool_executor =NewThreadpoolexecutor (Core_pool_size, Maximum_pool_size, Keep_alive, Timeunit.seconds, SPoolWorkQueue, sTh Readfactory);
It's a good practice to use a thread pool to manage threads in high concurrency scenarios, and I'm doing it myself. But when we look at the source of volley, we will find that volley actually does not use the thread pool, but maintains a 4-length array for multithreading management.
// Create network dispatchers (and corresponding threads) up to the pool size. for (int0; i < mDispatchers.length; i++) { new NetworkDispatcher(mNetworkQueue, mNetwork, mCache, mDelivery); mDispatchers[i] = networkDispatcher; networkDispatcher.start(); }
As we can see, when the network request is allocated, the network task taken from the queue is not given to the thread pool to allocate resources, but instead is given to an initialized thread array for control, so what does Networkdispatcher do?
Public voidRun () {Process.SetThreadPriority (Process.Thread_priority_background); Request request; while(true) {try {//Take a request from the queue.Request=Mqueue. Take(); } catch (Interruptedexception e) {//We may have been interrupted because it is time to quit. if(Mquit) {return; } continue; } try {request.Addmarker (Network-queue-take);//If The request was cancelled already, does not perform the //Network request. if(Request.IsCanceled ()) {Request.Finish (Network-discard-cancelled); Continue }//Tag the request (if API >=) if(Build.VERSION.Sdk_int>=Build.Version_codes.Ice_cream_sandwich) {Trafficstats.Setthreadstatstag (Request.Gettrafficstatstag ()); }//Perform the network request.Networkresponse Networkresponse=Mnetwork.Performrequest (Request); Request.Addmarker (Network-http-complete);//IF the server returned 304 and we delivered a response already, //We ' re done--don ' t deliver a second identical response. if(Networkresponse.Notmodified&&Request.Hashadresponsedelivered ()) {Request.Finish not-modified); Continue }//Parse The response here on the worker thread.Response<!--?-->Response=Request.Parsenetworkresponse (Networkresponse); Request.Addmarker (Network-parse-complete);//Write to cache if applicable. //todo:only update cache metadata instead of entire record for 304s. if(Request.Shouldcache ()&&Response.CacheEntry!= NULL) {Mcache.Put (Request.Getcachekey (), response.CacheEntry); Request.Addmarker (Network-cache-written); }//Post the response back.Request.Markdelivered (); Mdelivery.Postresponse (request, response); } catch (Volleyerror volleyerror) {parseanddelivernetworkerror (request, volleyerror); } catch (Exception e) {Volleylog.E (E, unhandled exception%S, E.ToString ()); Mdelivery.Posterror (Request,NewVolleyerror (e)); } }}
As we mentioned above, Blockingqueue is a thread-blocking queue, so when the queue is empty, the consumer thread blocks the commit waiting for the network task, so in while (true) {}, request = Mqueue.take (); This code is a thread-blocking operation, Mquit is used to control the end of the thread to release resources, if the network request is not cancel, and finally executes Mdelivery.postresponse (request, response) to pass the result callback to the main thread. We didn't see threadpoolexecutor in the whole process. Why use arrays instead of thread pools?
Let's start with a look at the thread pool scheduling rules Threadpoolexecutor usage Introduction
When a task is added to the thread pool by the Execute (Runnable) method:
-
If the number of threads in the thread pool is less than corepoolsize at this point, even if the threads in the thread pool are idle, a new thread is created to handle the task being added.
-
If the number in the thread pool is equal to corepoolsize, but the buffer queue Workqueue is not full, then the task is placed in the buffer queue.
-
If the number of threads in the thread pool is greater than corepoolsize, the buffer queue Workqueue full, and the number of thread pools is less than maximumpoolsize, a new thread is built to handle the task being added.
-
If the number of threads in the thread pool is greater than corepoolsize, the buffer queue is workqueue full, and the number in the thread pool equals maximumpoolsize, the task is handled by handler the policy specified. That is: the priority of the processing task is: Core thread corepoolsize, Task queue workqueue, maximum thread maximumpoolsize, if all three are full, use handler to handle the rejected task.
-
When the number of threads in the thread pool is greater than
Corepoolsize, if a thread is idle longer than KeepAliveTime, the thread is terminated. This allows the thread pool to dynamically adjust the number of threads in the pool.
In the online pool, if the number of threads in the thread pool is less than corepoolsize, even if the threads in the thread pool are idle, a new thread is created to handle the task being added, which means that the process resources are wasted when the corepoolsize is not full. Instead of requesting thread resources at run time, allocating thread resources during initialization can save creation expenses. So it seems that volley using a mdispatchers[i] to manage the multi-threading of network requests is also an optimization scheme.
Here is a single article on the processing of multithreading, summed up in the programming of the network framework of concurrent processing, we need to consider the following three points:
1. High concurrent thread execution efficiency for network requests
2. Priority processing and cancellation of queue for request queue
3. Multi-threaded resource allocation and release
In the next article I will describe in detail how to use httpurlconnection for the encapsulation of the request header, the concatenation of the data messages, and take you through several common network request protocols defined under the RFC document.
My Android Network Framework Tour (II)