Monday, June 29, 2009

Concurrency In using AsyncTask class (Android1.5)

I found that two AsyncTasks do not work concurrently. I investigated a bit and found a workaround .AsyncTask allows the app to do a task on a thread other than the UI thread. But IIUC, it only provides a single thread on which a queue of tasks is performed. Therefore, if one of the task is to wait on some event (n/w or sleep) then all other tasks will wait for it to finish.

To elaborate with the coding example:


public class MyTask extends AsyncTask<...>
{ ... }

// On the UI thread execute two tasks
MyTask mt1 = new MyTask().execute(args);

MyTask mt2 = new MyTask().execute(args);


In the above code both the execute calls will return immediately and free up
the UI thread; however mt1 will be executed first and mt2 will have to wait
until mt1 finishes.

Thanks to the android's open source, we can see implementation of AsyncTask.
http://google.com/codesearch/p?hl=en&sa=N&cd=2&ct=rc#uX1GffpyOZk/core...

I copied AsyncTask.java as UserTask.java in my project and changed the value
of CORE_POOL_SIZE to 5. This makes the thread pool to use 5 threads to
multiplex the queued AsyncTasks. This indeed solved my problem. Now if mt1
blocks on a sleep; mt2 goes ahead and finishes its job.

No comments: