What makes retrofit faster than HttpUrlConnection + AsyncTask? - android

The following blog gives comparison between the speed of the various Android Async Http Clients. Can someone explain what makes retrofit so ridiculously fast?

EDIT: After going through the blog post again, the single-vs-multi thread issue might not be true. The problem is that they didn't share the gory details of their profiling/benchmarking; that single set of numbers doesn't provide much insight. They state, "we determined that retrieving data from the API (the networking) was the bottleneck" but they don't break that down much. Did they make all the Volley and Retrofit requests single-threaded? Did they try to multi-thread their AsyncTasks so they could compare apples to apples? They don't specify.
If parsing a response into a JSONObject is slowing your app, one approach I have taken is using a JSONReader to parse the response in an event-driven manner. This may involve more code, but the benefit is that you get fine-grained control, so you can skip over things and not waste cycles parsing values that you don't care about. Depending on your application, this alone could speed things up quite a bit.
Personally, I find their assertion that Retrofit is easier to use as a more compelling reason to choose it for handling server access in my app.
From the AsyncTask doc under "Order of Execution":
When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.
If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.
This means that each request is waiting not only for the previous request to complete, but for all its JSON to be read/parsed as well.
Whereas AsyncTask is by default single-threaded, Retrofit is not. For the test to be fair, they should have used the ThreadPoolExecutor for the AsyncTasks. Not pointing out this distinction borders on disingenuous. I'd be very surprised that they were not aware of the single-threaded nature of AsyncTask.

Related

How to use RxJava for asynchronously executing a dynamic list of consecutive dependent operations?

I'm working on an Android Service Library (AAR) that has to execute a variable number of processes consecutive/pipelined on an input (JSON) in the background.
Thereby, the next process takes the output of the previous process as input.
The processes can involve literally every kind of possibly long running tasks (http requests, IO/DB requests, heavy data crunching, ...)
It shall be possible to log the progress between every process and get the final output of the last process e.g. in a subscriber (library service thread).
The processes should run stable, in case internet connection is lost or parent application state is changing.
I'm currently using Robospice in my library to achieve stability for multiple requests...
This question: How to implement a sequence of consecutive operations using rxjava
is related to my question, except I ask for a variable sequence of operations.
Is it possible achieve this with Rxjava? If yes, how? If not, what are other options?
My idea how to do it somehow without Rxjava:
Keep Process count for every request
Processes[counter].execute(result, callback)
Callback-OnSuccess(result): increase process counter and start Processes[counter] with result
But I'm not experienced with thread handling and think this is not very robust and maybe it doesn't even work or blocks the calling thread (what makes the library not usable for this time)

What is the best practice for a multiple request at same time

I have to send four different request in an api at the same time. Do i need to make AsyncTask background thread for each request or all request could be done through a single AsyncTask. Can somebody please help.
This is a concurrency issue. There is literally dozens of ways to do this in Android. I've written almost every single one for courses that cover this material... and even then it isn't 'simple'.
I'd personally make use of HaMeR (Handler, Messages, Runnable) framework of Android. Create 4 runnables and have them post their results to a Handler.
However... That isn't the easiest to implement. and would require you to understand how to safely create your own custom handler (making use of WeakReference properly, etc.)
Therefore, I'd recommend running the asyncTask(s) on the executorService
myTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); The default thread pool executor should start with 4 threads (I believe off-hand without looking it up).
I am assuming you are using HttpURLConnections. Unfortunately each of those connections, as specified in the documentation, is capable of handling only a single request.
However, you can (and possibly should) still perform all your requests in a single AsyncTask. Each AsyncTask will require the creation of a new thread which takes lots of time and resources. So don't listen to anyone who tells you to create a new task for each request.
You also have the option of exploiting HTTP persistence. If you add the header Connection: Keep-Alive to your request via connection.setRequestProperty("Connection", "Keep-Alive");, you will be able to send multiple requests over the same connection and save a lot of time and resources.
It's a little complicated in Java, because of the one-request-per-httpurlconnection rule, but it can be done. First, when you are done with your first request's HttpURLConnection do not close that connection. Then, to create the next connection, call url.openConnection() on the same URL object that you used to create your first HttpURLConnection. The JVM will know to reuse that connection if possible to save bandwidth.
You also have the option of using HTTP/2.0 multiplexing, which allows you to send multiple requests literally at the same time. Unfortunately I am not yet well versed enough in HTTP/2.0 to tell you exactly how to make use of this, but the multiplexing feature was included to solve exactly this problem.

Multiple AsyncTask vs multiple requests within one AsyncTask

I'm following this tutorial to create an XML reader with options to download multiple feeds at once. Are there any downsides to executing multiple AsyncTasks (max 3) simultaneously? I'm going to add a timer to check if they finished.
Running multiple AsyncTasks at the same time -- not possible? It is possible. However it could be, that due to the cpu depending on each device, one is faster than the other. But as #Alex already answered, you wont get "real" multitasking. Haven't it tried yet I would assume, that doing it all in one AsyncTask is faster. And you could reuse the connection you established to the server.
For better architecture I'll choose 1 AsyncTask per request. It is easier to manage actual request. Also it would be easier to modify (add/remove request).
Downsides of executing multiple AsyncTasks depend on your knowledge of AsyncTask lifecycle. You need to execute it correctly (depends on android version).
Good article about the dark side of Async tasks http://bon-app-etit.blogspot.com.by/2013/04/the-dark-side-of-asynctask.html
They won't be run simultaneously, but serially. See here:
When first introduced, AsyncTasks were executed serially on a single
background thread. Starting with DONUT, this was changed to a pool of
threads allowing multiple tasks to operate in parallel. Starting with
HONEYCOMB, tasks are executed on a single thread to avoid common
application errors caused by parallel execution.
If you truly want parallel execution, you can invoke
executeOnExecutor(java.util.concurrent.Executor, Object[]) with
THREAD_POOL_EXECUTOR

Using OKHttp, what is the difference between synchronous request in AsyncTask and OKhttp Asynchronous request?

OKHttp supports both synchronous and asynchronous api.
If I want to issue an async request, I can:
Use a AsyncTask, and issue OKhttp synchronous api.
Issue a OKhttp asynchronous api.
What is the difference between these 2 options? And which one is better?
Quite a lot differs!
Using AsyncTask for HTTP requests is pretty much one of the worst things you can do on Android. It's fraught with problems and gotchas that are best unconditionally avoided. For example, you cannot cancel a request during execution. The patterns of using AsyncTask also commonly leak a reference to an Activity, a cardinal sin of Android development.
OkHttp's async is vastly superior for many reasons:
It supports native canceling. If a request is in-flight, the reference to the Callback is freed and will never be called. Additionally, if the request has not started yet it never will be executed. If you are using HTTP/2 or SPDY we can actually cancel mid-request saving bandwidth and power.
It supports tagging multiple requests and canceling them all with a single method call. This means every request you make in, say, an Activity can be tagged with the Activity instance. Then in onPause or onStop you can cancel all requests tagged with the Activity instance.
If you are using HTTP/2 or SPDY requests and responses are multiplexed over a single connection to the remote server and by using the asynchronous Call mechanism this is much more efficient than the blocking version.
So if you can, use Call.enqueue!
Nothing much. OKHttp async is OKHttp API driven. So as long as you bundle the jars together for all platforms you should be good. AsyncTask is Android way of doing things.
However since Honeycomb Async task runs the tasks sequentially and not in parallel. This means that though the execute method of AsyncTask spans a new thread which runs your job away from the UI thread but all the tasks sent to one AsyncTask run in the same spanned thread.
So for 3 tasks submitted u don't get 3 threads they all run sequentially on a single spanned thread. With OKHttp you can achieve true parallelism using callbacks and async GET and POST.
Though you can do true parallelism in AsyncTask methods as well (check the overloaded execute methods in AsyncTask) but default Android behavior is not to do so.

Multiple HTTP POST in sequence

I have an app underdevelopment and I need to do 3 HTTP POSTs in sequence. What is the best way to implement this ? Should I
Make each HTTP Post in it own Async Class and daisy chain the Async classes(i.e. call the second async from the onPostExecute of the first Async)
Put all the HTTP POSTs in the doInBcakGround of a single Async.
I know how to do a HTTP POST request and I am using the OKHTTP lib. I just would like to know that the best practice it for multiple POSTs in sequence.
Cheers
Your first approach will be better and quite modular as you can keep the track of anything in your application.In the three different AsyncTask you can have a check in postExceute() that which AsyncTask is done with its work (more easily and precisely) AND
>>>>>In case if the application gets Crashed
then which of the httpPost failed. However , the second one will make your code messy and you will be unable to track on getting Exception that which httpPost request failed(in a straight forward way though).
So Launching your second AsyncTask from onPostExecute of your first task will be better approach.
See here too : Calling an AsyncTask from another AsyncTask
Both 1 and 2 approaches make app ANR, so better to for other approach.
You can use ExecutorService that executes each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods.
Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead, and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.
here is more deatias
http://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor.html
Put all the HTTP POSTs in the doInBcakGround of a single Async.
because all your posts handle in one module.
dose not have overhead of creating asyntask and GC may not call as many as your first.
you do not need to check internet connection 3 times you have to check it one time
all exception handles one time but in approach 1 you have to copy and paste all exception handler that may occurs. and always recommended not to repeat yourself. if you can do something to not copy and paste codes, do it.
At the end I prefer approach 2.

Categories

Resources