How does the handler message queue work? I know for a fact that the message queue is tied to the thread it is initialized in. If i have 2 tasks(each download from the web), and I initiate an async task from the handler,one for each, will the 2 tasks be executed simultaneously?
I just need to understand, how the queue works..
could anyone please help! :)
First of all, AsyncTask can be executed only on the UI thread. So, even if you have two separate handlers (one for each AsyncTask) they should be both associated with the UI thread.
Secondary, several AsyncTask instances may run either simultaneously or one by one. It depends on the API version. It is better to read documentation about this:
public final AsyncTask execute (Params... params)
Executes the task with the specified parameters.
The task returns itself (this) so that the caller can keep a reference
to it.
Note: this function schedules the task on a queue for a single
background thread or pool of threads depending on the platform
version. 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 HONEYCOMB, tasks are back to being executed on a single
thread to avoid common application errors caused by parallel
execution. If you truly want parallel execution, you can use the
executeOnExecutor(Executor, Params...) version of this method with
THREAD_POOL_EXECUTOR; however, see commentary there for warnings on
its use.
Related
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
android Asynctask has been modified quite frequently between different API-levels. I'm developing an Application in which i've to upload images to FTP server. i want to do that in serialized order (images upload after one-another by one image upload per asyntask). I understand the SERIAL_EXECUTOR and THREAD_POOL_EXECUTOR stuff, but i just want some clarity about what is the default behavior of asynctask ( my min. target API is ICS 4.0 ). if i simply execute say 10 asyncs' in a loop, will they go to thread queue and execute one by one or they'll just go parallel ?
Look in the AsyncTask documentation:
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.
So, with min target of 14, they will be serialized.
You can't use one async task with loop inside doInBackground()? If you want to have control over them, you can invoke second async task in onPostExecute() of first.
Do I need to call cancel on an asyncTask in a fragment onDestroy event in case the asynchronous task hasn't finished yet when the user hits the back button and leaves the activity?
Do I need to also possibly check whether an existing instance of my asyncTask may still be running in case the asyncTask from the previous visit to the fragmentActivity is still running, hasn't finished or hasn't yet been cancelled?
You don't have to, but you should.
The reason is that it keeps running till it finishes, and starting on honeycomb, it even uses only one thread for all asyncTasks.
Anyway, asyncTask should be usually used for short time tasks, something like 1-10 seconds. It's not a rule, but it will help you achieve the reason why there is an asyncTask - to be able to run tasks in the background.
Here are some notes about asyncTask from the API :
"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."
API of execute():
"Starting HONEYCOMB, tasks are back to being executed on a single
thread to avoid common application errors caused by parallel
execution. If you truly want parallel execution, you can use the
executeOnExecutor(Executor, Params...) version of this method with
THREAD_POOL_EXECUTOR; however, see commentary there for warnings on
its use."
If you wish to use asyncTask as a background task anyway, verify that there is only one single instance of it (and don't forget to cancel it when not needed), or use the next code which Google recommends to avoid:
public static <T> void runAsyncTaskInMultipleThreads(final AsyncTask<T,?,?> asyncTask,final T... params)
{
if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.HONEYCOMB)
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,params);
else asyncTask.execute(params);
}
I have been reading Android documentation (AsyncTask, Thread) and vogella tutorial about this matter, but I have doubts yet.
For example, I want to send a message from an Android app to a server. And I would like this process to be responsive. What should I use?
I have seen examples where they create a new Thread for not block UI, but this way we don't have the progress of process, also you have to process the response within the Thread because the run() method doesn't returning anything.
AsyncTask seems better option than Thread, but I don't know what are the consequences of using an AsyncTask instead of a 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
All other answers here are not complete, there is a big difference between AsyncTask and Thread, i.e.
Thread can be triggered from any thread, main(UI) or background; but AsyncTask must be triggered from main thread.
Also on lower API of Android(not sure, maybe API level < 11), one instance of AsyncTask can be executed only once.
For more information read Difference between Android Service, Thread, IntentService and AsyncTask
In general
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
in general using of 2 this features are equivalent, but AsyncTask is more simple in terms of integration with GUI
I would prefer to Use Async Task as it will let you know when the
background process gets started and over and when can I parse
the response.
Async has methods like onPreExecute and onPostExecute which will allow us to do tasks before and after calling the background
tasks.
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.
You can control its own functions
doInBackground(Params... params),
onCancelled(),
onPostExecute(Result result),
onPreExecute(),
nProgressUpdate(Progress... values),
publishProgress(Progress... values)
AsyncTask enables proper and easy use of the UI thread. - from Developer.
The thing is - AsyncTask is a special kind of Thread - one which is a GUI thread, it works in the background and also let's you do something with the GUI - it is basically "pre-programmed" for you with functions onPreExecute(), do inBackground(), onPostExecute().
In order to make Thread work that way, you have to write a loooot of code.
I have an Android application which has the main UI thread, and several other worker threads which I have spawned using ASyncTask.
However, there is a scenario that I can produce every time in which I attempt to spawn a new thread with ASyncTask using task.execute(), and it does not call doInBackground(). The thread never seems to start. Then my application seems to spin for a little while, and then begins to hang.
Here are the threads I am using:
And here is the memory usage on the device:
It does not look as though it is failing to spawn due to memory issues.
Is there some other underlying reason that I do not know of? Maximum number of threads? Is there any way for me to find out why it is not executing?
AsyncTask uses a ThreadPoolExecutor used internally with a core pool size of 5 and a LinkedBlockingQueue. In simpler terms: you can have atmost 5 AsyncTasks active at the same time. Additional tasks will be queued till one of the other AsyncTasks does not return from doInBackground().
You may want to review your code to free up some AsyncTasks. If thats not possible, you can try to create a CustomAsyncTask class in your project based on the original AsyncTask code which can be found here. Try setting the CORE_POOL_SIZE variable to a higher value or using a SynchronousQueue.
Did you read the docs?
Note: this function schedules the task on a queue for a single
background thread or pool of threads depending on the platform
version. 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. After
HONEYCOMB, it is planned to change this back to a single thread to
avoid common application errors caused by parallel execution. If you
truly want parallel execution, you can use the
executeOnExecutor(Executor, Params...) version of this method with
THREAD_POOL_EXECUTOR; however, see commentary there for warnings on
its use.
Source