Asynctask VS Thread in Android

Asynctask vs Thread in android

For long-running or CPU-intensive tasks, there are basically two ways to do this: Java threads, and Android's native AsyncTask.

Neither one is necessarily better than the other, but knowing when to use each call is essential to leveraging the system's performance to your benefit.

Use AsyncTask for:

  1. Simple network operations which do not require downloading a lot of data
  2. Disk-bound tasks that might take more than a few milliseconds

Use Java threads for:

  1. Network operations which involve moderate to large amounts of data (either uploading or downloading)
  2. High-CPU tasks which need to be run in the background
  3. Any task where you want to control the CPU usage relative to the GUI thread

And there are lot of good resources over internet which may help you:

http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html

Difference between AsyncTask and Thread/Runnable

AsyncTask is a convenience class for doing some work on a new thread and use the results on the thread from which it got called (usually the UI thread) when finished. It's just a wrapper which uses a couple of runnables but handles all the intricacies of creating the thread and handling messaging between the threads.

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

The Runnable interface is at the core of Java threading. The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.

Also if I quote from this blog:

if you need SIMPLE coding use AsyncTask and if you need SPEED use traditional java Thread.

Real difference between AsyncTask and Thread

Please read this blog

http://crazyaboutandroid.blogspot.in/2011/12/difference-between-android.html

and Details are:

Difference between Android Service,Thread,IntentService and AsyncTask

When to use ?

Service

   Task with no UI, but shouldn't be too long. Use threads within service for long tasks.

Thread

- Long task in general.

- For tasks in parallel use Multiple threads (traditional mechanisms)

AsyncTask

- Small task having to communicate with main thread.

- For tasks in parallel use multiple instances OR Executor

Android - Difference between Thread and AsyncTask?

When you use a Thread, you have to update the result on the main thread using the runOnUiThread() method, while an AsyncTask has the onPostExecute() method which automatically executes on the main thread after doInBackground() returns.

While there is no significant difference between these two in terms of "which is more beneficial", I think that the AsyncTask abstraction was devised so that a programmer doesn't have to synchronize the UI & worker threads. When using a Thread, it may not always be as simple as calling runOnUiThread(); it can get very tricky very fast. So if I were you, I'd stick to using AsyncTask and keep Thread for more specialized situations.

Asynctask vs Thread vs Services vs Loader

AysncTasks are not 'outdated' as much as they are incomplete.
Among other things async tasks do not bother if their parent activity is currently running or not. For the same reason why you include checks for verify the context to be null or not. Besides, unless you are using your own Thread Pool Executor these tasks execute serially.

Volley tries to fill in those gaps, mainly concerning syncing up with the main thread and thread pooling. It behaves optimal if you wish to do stuff that requires average network requests; like some meta data list and images(picture the youtube app requests and facebook app requests for posts).

Typically few advantages of Volley are as follows

  1. It keeps the worker thread informed about the activity(Main thread)
  2. Easier resource prioritization you could provide priority to your download requests.
    A typical scenario would involve you giving priority to text over image.
  3. Effective request cache and memory management.
  4. Extensible
  5. It provides you an option to discard your request in-case your activity was shutdown or restarted.
  6. Simpler patterns for data retrieval as opposed to AsyncTasks.

Volley fares badly when it comes to streaming requests/video as mentioned at Google I/O.

I'm not exactly aware of robospice.
Ps: If you have time on your hand see https://www.youtube.com/watch?v=yhv8l9F44qo

Here's a further read if you wish to go into other libraries with benchmarks for the same.
Comparison of Android networking libraries: OkHTTP, Retrofit, and Volley

Android AsyncTask vs Thread + Handler vs rxjava

Since no one's replying. I'm answering my own questions then.

  1. The reason why AsyncTask is recommended for only short tasks (around 5 seconds) is there is no method to cancel a running AsyncTask. There exists a method called AsyncTask.cancel(true) which invokes onCancelled(Result result). However, according to the docs, this method "runs on the UI thread after cancel(boolean) is invoked and doInBackground(Object[]) has finished." (https://developer.android.com/reference/android/os/AsyncTask.html). On the other hand, Thread can be stopped with Thread.interrupt().
  2. There shouldn't be any problem running an AsyncTask within a Service provided that you are aware of the cancellation limitation of AsyncTask and the possibility of memory leak can be created by AsyncTask. Note that, there is obviously no need to use an AsyncTask in an IntentService which is already running in a worker thread.
  3. This is a very experience-based question. I guess there would be no complete answer. What we can do is to understand Rx and being aware of the its limitations to determine where suitable to use it. In my development work, I use RxJava all the time without having any issue. Note that the same memory leaking issue is also applied to RxJava. You can perhaps find one of the specific questions here. There are also a whole bunch of discussions about handling leaking/screen rotation with RxJava that can be easily found by Googling.

Difference between Service, Async Task & Thread?

Probably you already read the documentation description about them, I won't repeat them, instead I will try to give answer with my own words, hope they will help you.

  • Service is like an Activity but has no user interface. Probably if you want to fetch the weather for example you won't create a blank activity for it, for this you will use a Service.

  • A Thread is a Thread, probably you already know it from other part. You need to know that you cannot update UI from a Thread. You need to use a Handler for this, but read further.

  • An AsyncTask is an intelligent Thread that is advised to be used. Intelligent as it can help with it's methods, and there are three methods that run on UI thread, which is good to update UI components.

I am using Services, AsyncTasks frequently. Thread less, or not at all, as I can do almost everything with AsyncTask.

Handler vs AsyncTask vs Thread

As the Tutorial on Android background processing with Handlers, AsyncTask and Loaders on the Vogella site puts it:

The Handler class can be used to register to a thread and provides a simple channel to send data to this thread.

The AsyncTask class encapsulates the creation of a background process and the synchronization with the main thread. It also supports reporting progress of the running tasks.

And a Thread is basically the core element of multithreading which a developer can use with the following disadvantage:

If you use Java threads you have to handle the following requirements
in your own code:

  • Synchronization with the main thread if you post back results to the user interface
  • No default for canceling the thread
  • No default thread pooling
  • No default for handling configuration changes in Android

And regarding the AsyncTask, as the Android Developer's Reference puts it:

AsyncTask enables proper and easy use of the UI thread. This class
allows to perform background operations and publish results on the UI
thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler
and does not constitute a generic threading framework. AsyncTasks
should ideally be used for short operations (a few seconds at the
most.) If you need to keep threads running for long periods of time,
it is highly recommended you use the various APIs provided by the
java.util.concurrent package such as Executor, ThreadPoolExecutor and
FutureTask.

Update May 2015: I found an excellent series of lectures covering this topic.

This is the Google Search: Douglas Schmidt lecture android concurrency and synchronisation

This is the video of the first lecture on YouTube

All this is part of the CS 282 (2013): Systems Programming for Android from the Vanderbilt University. Here's the YouTube Playlist

Douglas Schmidt seems to be an excellent lecturer

Important: If you are at a point where you are considering to use AsyncTask to solve your threading issues, you should first check out ReactiveX/RxAndroid for a possibly more appropriate programming pattern. A very good resource for getting an overview is Learning RxJava 2 for Android by example.



Related Topics



Leave a reply



Submit