title: synchronization strategy for android async task
body: <p>I am trying to implement a simple synchronization strategy in android.</p>
  
  <p>A service instantiates class A and calls it's method <code>sendToServer()</code> for every iteration of a loop. This results in multiple Async tasks being started and the service ends immediately. The service may run again anytime and repeat the process.</p>
  
  <p>So, to prevent two Async tasks from taking the same input, i store the Ids in a synchronized list and check the list before i start the async task.</p>
  
  <p>But i am confused which piece of code i need to put in a <code>synchronized</code> block? Do i define the entire method <code>isAlreadyRunning()</code> as <code>synchronized</code>? Or do i not need to define any synchronized block of code at all?</p>
  
  <p>Here is my class :</p>
  
  <pre><code>public class A{
      private static List&lt;Integer&gt; idList = Collections.synchronizedList(new ArrayList&lt;Integer&gt;());
  
      private boolean isAlreadyRunning(id){
          //iterate through the list and return true if the id is already present
          ....
          }
  
      private class sendToServerAsyncTask extends AsyncTask&lt;Void, Void, Boolean&gt;{
          @Override
          protected Boolean doInBackground(Void... params) {
              //send http request 
              }
  
          @Override
          protected void onPostExecute(Boolean result){
              idList.remove(id);
              }
          }
  
      public void sendToServer(int id) {
          if(isAlreadyRunning(id)){
              // an async task is already running for this id.
              //,so dont start the async task again, just exit
              return; 
          else {
              idList.add(id);
              new sendToServerAsyncTask(id).execute();
              }
  
  
          }
      }
  </code></pre>