I have the following class and inner "AsyncTask" (http://developer.android.com/reference/android/os/AsyncTask.html) defined.
class SomeClassA {
Long b = 0;
void executeTask() {
// executed on main thread.
b = 1;
new SomeAsyncTask().execute();
}
private class SomeAsyncTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
b = 3;
}
protected void onPostExecute(Void param) {
System.out.println(b);
}
}
}
I am curious about what guarantees I am given about the "memory visibility" of an AsyncTask as well as thread safety. From my understanding, the call "doInBackground" is executed in a separate thread, and therefore any changes I make to "b" in "doInBackground" cannot be guaranteed to be "visible" in any of the callbacks executed on the main thread (e.g. "onPostExecute()", "onPreExecute", "onProgressUpdate" etc.).
Is this correct? So in the above example, the "System.out.println(b)" in "onPostExecute" can print 1 OR 3 but it's not guaranteed. What would I have to do to guarantee this memory observability?
In the AsyncTask website (posted above), I see the following snippet.
Memory Observability
AsyncTask guarantees that all callback calls are synchronized in such a way that the following operations are safe without explicit synchronizations.
- Set member fields in the constructor or onPreExecute(), and refer to them in doInBackground(Params...).
- Set member fields in doInBackground(Params...), and refer to them in onProgressUpdate(Progress...) and onPostExecute(Result).
I think this "might" explain my confusion but I don't understand what this means. Can someone explain this to me?