Overview
Volley is a network library launched by Google in 2013 to solve network request problems in complex network environments. It was very popular when it was first launched, and now there are few changes in the project. The project library address is /platform/frameworks/volley
Through the submission history, we can see that the last modification has been a while since today. The release version of the volley package has not been updated for a long time.
author JeffDavidson<jpd@> SunMar1316:35:592016+0000 Although it has not been updated for a long time, Volley has always been a good network framework. Let’s analyze the source code of Volley to better understand the usage scenarios, design patterns, and some minor problems, or problems caused by improper use.
Create a RequestQueue
The following code snippet shows the steps required to create a RequestQueue:
// Initialize RequestQueue with cache and networkmRequestQueue = new RequestQueue(cache, network); // Start the queue(); String url =""; // Clearly describe the request and process the responseStringRequest stringRequest = new StringRequest(, url, new <String>() { @Override public void onResponse(String response) { // Process response information } }, new () { @Override public void onErrorResponse(VolleyError error) { // Handle error } }); // Add request to RequestQueue.(stringRequest); // ...
The Volley class essentially only provides a method newRequestQueue to create a RequestQueue. RequestQueue is the request queue of the volume. mCurrentRequests stores the execution and the requests to be executed. DEFAULT_NETWORK_THREAD_POOL_SIZE is a constant 4.
You can modify the number of threads through the publicRequestQueue (Cachecache, Networknetwork, intthreadPoolSize) method of RequestQueue, and enable 4 threads by default, and then run the sub-background. Here we need to note that when calling Volley's RequestQueue, the start method of RequestQueue has been called internally, and there is no need to call it again. If you create your own RequestQueue, you need to call the start method yourself, and you can use it once during the entire APP life cycle. Multiple calls will increase thread overhead. Each time you call the start method, the stop method will be called to terminate the original thread and then restart the new thread.
The number of threads requested in the background is fixed when using volley. The default 4 concurrency does not require modification. It may be based on this consideration. The Executor thread pool is not used. The thread pool consideration itself is to manage frequent thread creation and avoid excessive overhead. There are always 4 threads by default, and there is no overhead problem. I personally feel that using thread pools here will be better, of course, the complexity of introducing thread pools will definitely increase. Always only have 4 threads also raise some problems, making volley unsuitable in some scenarios. If the request server responds too long, the 4 threads will be blocked. At this time, the new request can only be waited and cannot be executed directly. Volley is more suitable for lightweight requests, with frequent requests and short request time.
/** Number of network request dispatcher threads to start. */ private static final int DEFAULT_NETWORK_THREAD_POOL_SIZE = 4;
public RequestQueue(Cache cache, Network network) { this(cache, network, DEFAULT_NETWORK_THREAD_POOL_SIZE); }
Network network = new BasicNetwork(stack); RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network); ();
Requesting the executor HttpStack
HttpStack is the interface that truly executes network requests. The performRequest method executes requests. There are two implementations in the source code, one is HurlStack and the other is HttpClientStack. The SDK version is greater than or equal to 9.
if (stack == null) { if (.SDK_INT >= 9) { stack = new HurlStack(); } else { // Prior to Gingerbread, HttpUrlConnection was unreliable. // See: /2011/09/ stack = new HttpClientStack((userAgent)); } }
DefaultHttpClient and its brother AndroidHttpClient are both specific implementation classes of HttpClient. They both have many APIs, and their implementation is relatively stable and the number of bugs is small. But at the same time, due to the excessive number of HttpClient APIs, it is difficult for us to upgrade and expand it without breaking compatibility. Therefore, the current Android team's working attitude towards improving and optimizing HttpClient is not active.
HttpURLConnection is a multi-purpose, extremely lightweight HTTP client that uses it to perform HTTP operations to be suitable for most applications. Although the HttpURLConnection API provides relatively simple, it also makes it easier to use and extend it. However, before Android 2.2 version, HttpURLConnection had some annoying bugs. For example, when calling the close method to a readable InputStream, the connection pool may fail. Then our usual solution is to directly disable the connection pool function. Before Android 2.3 version, HttpURLConnection has bugs and is not recommended to use them. In Android 2.3 version and later, HttpURLConnection is the best choice. Its API is simple and small, making it very suitable for Android projects. The compression and caching mechanism can effectively reduce the traffic of network access, and also play a major role in improving speed and saving power.
At present, we have a better request choice for okhttp. There is no request to encapsulate it in the volley source code. We can implement the HttpStack interface ourselves and use okhttp request in performRequest. Compared with other implementations, OkHttp has the following advantages: supports SPDY, allowing all requests connected to the same host to share a socket. If SPDY is not available, connection pooling is used to reduce request latency. Use GZIP to compress the download content, and the compression operation is transparent to the user. Use response caching to avoid duplicate network requests. When there is a problem with the network, OKHttp will still be effective and it will recover from common connection problems. If your server has multiple IP addresses, OKHttp will try to connect to other addresses when the first address fails, which is very necessary for IPV4 and IPV6 and services that are hosted in multiple data centers. Using OkHttp as an alternative is a good choice.
Cache and thread processing
It is inaccurate to say that there are 4 default threads, there are 4 NetworkDispatchers to perform network requests, and there is also a CacheDispatcher cache thread. The local cache policy needs to implement the Cache interface. There are two implementations of DiskBasedCache and NoCache in the source code. DiskBasedCache is used by default. We can implement the Cache interface according to our needs. The default path of DiskBasedCache is the volley in the app cache directory, and the default cache is 5M. After it exceeds, the old data will be overwritten.
Request class
The subclass of the Request class is equivalent to the input of volley and is used when creating a request. JsonObjectRequest and JsonArrayRequest are used to process data that is returned by json, StringRequest processes stirn, and ImageRequest is used to process images.
Volley is actually a producer and consumer system, the caller is the producer, while Volley is the consumer. The caller produces a Request through RequestQueue, and Vollery consumes a Request to obtain a Response. Then the one responsible for configuring these producers and consumers is the Dispatcher, which is the Dispatcher of Cache and Network.
Summarize
The above is all the detailed explanation of the use of Volley source code and usage scenarios in this article. I hope it will be helpful to everyone. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!