I understand that it's not safe to access a shared instance variable between multiple threads (unless the variable is declared volatile
and properly synchronized
). I'm trying to understand the semantics of passing a shared instance variable to a background thread using Android's AsyncTask
.
Consider the following code:
public class Example {
ContentValues contentValues;
public void start() {
contentValues = new ContentValues();
contentValues.put("one", 1);
new MyAsyncTask().execute(contentValues);
contentValues.put("two", 2);
}
class MyAsyncTask extends AsyncTask<ContentValues, Void, Boolean> {
@Override
public void onPreExecute() {
contentValues.put("three", 3);
}
@Override
protected Boolean doInBackground(ContentValues... cvs) {
ContentValues cv = cvs[0];
return cv == contentValues;
}
}
}
What do we know about the state of the local variable cv
in doInBackground()
? Specifically,
-
Which key-value pairs are guaranteed to be in it.
-
Which key-value pairs might be in it?
-
What will
doInBackground()
return?
from What is the behavior of instance variables passed between threads?
No comments:
Post a Comment