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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With