Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 937
Marian Paździoch Avatar asked Jul 15 '16 09:07

Marian Paździoch


1 Answers

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

like image 150
suitianshi Avatar answered Oct 10 '22 14:10

suitianshi