To force cancel AsyncTask shouldn't the flag periodically checked in doInBackground be volatile? By Admin

I want to force cancel AsyncTask. I see that you can use isCancelled() like in this valid solution (which under the hood uses AtomicBoolean.

But I see solutions like suspiciousSolution1, suspiciousSolution2, suspiciousSolution3 where there is new flag introduced private boolean isTaskCancelled = false;.

And I started wondering - since that flag is modified in

public void cancelTask(){
   isTaskCancelled = true;
}
which runs on SOME thread, and is read in

protected Void doInBackground( Void... ignoredParams ) {
    //Do some stuff
    if (isTaskCancelled()){
        return;
    }
}
which runs in WorkerThread, then shouldn't the flag isTaskCancelled be volatile (or AtomicBoolean as in Google's implementation).


  •  Open
  •  27-07-2016
  •  4
  •  270

Answers ( 4 )

 Posted on 27-07-2016

Yes, it should be volatile. Otherwise a write to the variable in thread A may not be visible to a read in thread B due to optimizaton(by compiler, JVM, etc). See this

 Posted on 27-07-2016

Yes, volatile. Considering that you are only using this to periodically check your asynctask. If it were multiple threads I would suggest using atomic fields. Pls see more information here: volatile vs atomic & Volatile boolean vs AtomicBoolean

 

 Posted on 27-07-2016

Try This

Initialize
  private AysncTask aysncTask;
Task Call
   aysncTask=new AysncTask();
        aysncTask.execute();
Task Cancel Where You WANT
  if ( aysncTask != null && aysncTask.getStatus() == aysncTask.Status.RUNNING ){
        aysncTask.cancel(true);

    }

 Posted on 27-07-2016
I suggest you that please replace your asynctask with others cause its very old and and as like other response that you get also delay than other. I would like to refer you this link for comperisions. Hope it will help you.
http://instructure.github.io/blog/2013/12/09/volley-vs-retrofit/