Issue
In my Android app, I figured out that all my api calls are being queued instead of happening concurrently. I'm assuming they are all being posted to the same thread, while I was under the impression that an AsyncTask
creates a new thread for doInBackground()
.
public class API extends AsyncTask<String, String, String> {
public interface Listener {
void completedWithResult(JSONObject result);
}
public Listener listener;
@Override
protected String doInBackground(String... strings) {
if(!canMakeRequest()){
return internetError().toString();
}
String action = strings[0];
Log.i("API", action +" Sent");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("API", action +" Received");
return "";
}
@Override
protected void onPostExecute(String json) {
JSONObject obj;
obj = new JSONObject(json);
if(listener != null)listener.completedWithResult(obj);
}
}
In a whole bunch of places in my app I have things like:
API api = new API();
api.listener = new API.Listener() {
@Override
public void completedWithResult(JSONObject result) {
Log.i(tag, "Returned with "+result);
}
};
api.execute("update-address/");
And I always create a new instance of API
, but my logs have all of these calls happening serially and not in parrallel:
analytics/log/ Sent
analytics/log/ Returned
get-beta-tester Sent
get-beta-tester Returned
get-following Sent
get-following Returned
get-groups Sent
get-groups Returned
get-follow-requests Sent
get-follow-requests Returned
get-followers Sent
get-followers Returned
analytics/log/ Sent
analytics/log/ Returned
analytics/log/ Sent
analytics/log/ Returned
post-session Sent
post-session Returned
analytics/log/ Sent
analytics/log/ Returned
post-session Sent
post-session Returned
analytics/log/ Sent
analytics/log/ Returned
analytics/log/ Sent
analytics/log/ Returned
unregister-GCM Sent
unregister-GCM Returned
analytics/log/ Sent
analytics/log/ Returned
verify Sent
verify Returned
Solution
See here:
https://developer.android.com/reference/android/os/AsyncTask.html
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.
and the solution is to:
If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.
api.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "update-address/");
Answered By - marcinj
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.