Search code examples
androidmultithreadingandroid-asynctasksynchronizedvolatile

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


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).


Solution

  • 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