If I have a button action that launches an AsyncTask. What if I click the button 10 times? Is the task executes 10 times and runs that much in background? Or is any previous task canceled and just the task reinitiated (that would be my desired behaviour)?
public void myButtonClick(View v) {
new MyAsyncTask().execute(params);
}
If you really want to keep the task to a single execution at a time, you should create a single threaded ThreadPool:
If you do it as suggested above, you’ll get a RejectedExecutionException if you try to submit a task while one is already running. When that happens, you can cancel the last one submitted, and schedule a new execution. Keep in mind your task has to be interruptible (be careful with InputStream/OutputStream as they are not interruptible, use Channel objects instead).
The lock is needed so that you serialize the submission attempts. A thread could still get a RejectedExecutionException if another thread submitted a task during the catch block execution.