Which AsyncTask should I use behind SERIAL_EXECUTOR in Android - android

I am retrieving already created data in all user controls. And there are 3 Spinners so I am using SERIAL_EXECUTOR to execute it one by one. But now, issue is that, one Spinner retrieves data based on another Spinner.
So which AsyncTask executor should I use for that Spinner by which It can load its data although SERIAL_EXECUTOR is going on.
In short, I want to know which AsyncTask should I use which will execute that Task even though SERIAL_EXECUTOR is in process.

If you want to execute an AsyncTask parallel to another one then you can use THREAD_POOL_EXECUTOR like this:
AsyncTask task = new SomeAsyncTask();
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
But I warn you that this might not work as good as you might like. If the AsyncTasks you are executing perform quite a bit of work on their own than executing them in parallel will slow them down considerably. If possible, try to execute tasks serially, only execute in parallel if you absolutely have to. If you need to load data which is dependent on some other kind of data consider doing it in one big AsyncTask instead of splitting the work to to AsyncTasks. Always try to keep the amount of AsyncTasks or Threads to a minimum. The fewer you have the faster your app will load.

Related

android loop inside asynctask or asynctask inside loop

I have list of items to be syncronized with cloud. Let's say it has 10 items, so I have to make 10 HTTP requests to server. The question is: which approach should I use and why?
foreach loop inside one async task
10 async tasks inside foreach loop?
Better would be to have one AsyncTask and loop in in. And here is why:
All AsyncTasks will by default on one background thread (with API 11+, eg Honeycomb), so your 10 tasks will still execute sequentially, but meanwhile will take much more memory. So it's really better to run only one AsyncTask and if you need - publishProgress on execution process.
Here is SO answer about having multiple AsyncTasks.
Another approach is passing Executor to your AsyncTask, so it can break the limit of simultaneously runned AsyncTasks. But still it can be really memory consuming.
Aslo you might want to read this Android Developers guide.

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

Can you have two AsyncTasks in one Activity?

I have already developed an Activity which will parse JSON data and display the results in a ListView. I am using an AsyncTask for this purpose.
What I want now is that, when I click on an item in the ListView, the file should start downloading. Can I write another AsyncTask in the same activity so that this AsyncTask will do the downloading work for me? Is there any problem with having multiple AsyncTasks in the same activity?
As per from the Doc yes you can.
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.
BEst answer How is itself on stackoverflow.
There shouldn't be any problem with multiple Asynctasks in a single activity. You should be careful to clearly define the values that each one manipulates (for example, if task B relies on a value given by task A, make sure that A must finish first), but in general, it should be fine. I have a project right now with three asynctasks running upon first install, and it's ticking along fine thus far.
Yes.. You can.
AsyncTask is simple thread handler implementation.

Android: Future/FutureTask for parallel processing of data

I am trying to optimize a complex data updater and parser for my Android app. The server provides three interface functions. The parser requires the data from all those three functions.
When the download of the data is finished, the parser can start. It consists of many different independent tasks which can be parallelized.
I was thinking of using Futures or FutureTasks for processing the data.
So basically, this is the procedure:
create Task-1, Task-2, Task-3 for downloading the data
wait for the downloads to be finished
create Task-1,..., Task-N for parsing the data
wait for the parser to be finished
call a callback to signal that process is done.
My first question: is it possible to create Futures with asynchronous functions, which use callbacks to return the data (network framework)?
Second question: are there any drawbacks in using Futures or FutureTasks respectively in this scenario or are there any better solutions to achieve that?
Thank you.
Basically you are Trying to achieve the following.
Step 1 - User from UI starts 1,2,... n download tasks.
Step 2 - Once each of the task is completed, new thread should be started to process it.
Step 3 - Once all n Tasks are completed, UI should be updated ... may be with a success dialog.
This can be achieved easily by using Async Task. I am going to tell you the approach and not the code sample.
Things to note about Async Task
Before 1.6, Async Task handles all background operations with a single additional thread.
After 1.6 till 3.0 .. it was changed, so that a pool of thread had begun to be used. And operations could be processed simultaneously.
Since Honeycomb default behavior is switched back to use of a single worker thread (one by one processing).
How to implement your requirement
For your requirement, you can use the method (executeOnExecutor) to run simultaneous tasks (1 till n tasks) if you wish (there two different standard executors: SERIAL_EXECUTOR and THREAD_POOL_EXECUTOR).
The way how tasks are enqueued also depends on what executor you use. In case of a parallel one you are restricted with a limit of 10 (new LinkedBlockingQueue(10)). In case of a serial one you are not limited (new ArrayDeque()).
So the way your tasks are processed depends on how you run them and what SDK version you run them on. As for thread limits, we are not guaranteed with any, yet looking at the ICS source code we can say that number of threads in the pool can vary in range 5..128.
When you start too many tasks (like 100s or more) with default execute method serial executor is used. Since tasks that cannot be processed immediately are enqueued you get OutOfMemoryError (thousands of tasks are added to the array backed queue).
Exact number of tasks you can start at once depends on the memory class of the device you are running on and, again, on executor you use.
So by following this approach, once all the tasks are completed, you can use a handler to update the UI.
Hope this helps.

AsyncTask v/s ThreadPoolExecutor for network request

I am working on a project where i need to hit a web service download the data which is JSON and will be represented in a list. And all the list items have there thumbnail url's which would be downloaded and displayed in the list item.
I have done the entire calling part with both a ThreadPoolExecutor and a AsyncTask.
But from a design perspective which is a better option out of:
1. ThreadPoolExecutor
2. AsyncTask
Few adv. of ThreadPoolExecutor:
1. User can define no. of concurrent threads that can be executed.
2. Cancelling all the request at once.
Few adv. of AsyncTask:
1. Internally it uses a ThreadPoolExecutor, however we cant define no. of threads that run simultaneously.
2. Cancelling a single request is easy.
3. Ability to attach and detach a task.
4. Updating the UI from doInBackground is simple.
I know more advantages of AsyncTask, however for a simple application like fetching data from a web service and later on fetching images.
Which would be more appropriate a AsyncTask or ThreadPoolExecutor? If you can provide a few reasons regarding your choice it would be helpful.
I have read a few article here on SO but none that compares the two. If there are any that i missed sorry for the trouble could you please post me the link for the same.
Thanks in advance.
I consider that AsyncTask is useful if you want to load thumbnail using a series "cascade-call": in the onPostExecute, you can start the next AsyncTask to download the next thumbnail.
But if you want to improve efficiency, I suggest using ThreadPoolExecutor. This is a sentence from developer.android.com:
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.
In conclusion, ThreadPoolExecutor was probably designed for cases such as your; for this reason, I suggest you this class.

Categories

Resources