Issue
I have an AsyncTask
class that I would like to pass some primitive parameters to it through its constructor
.
Then do some manipulation on variables in onPreExecute
(Running in Main Thread) method and then use the variables inside doInBackground
(Running in a worker Thread). Is it OK to do that? Or it does need some sort of synchronization?
private class MyClass extends AsyncTask<Void, Void, Void> {
//shared variables
Long Num1;
int Num2;
private MyClass (Long num1, int num2){
Num1 = num1;
Num2 = num2;
}
@Override
protected void onPreExecute() {
//do some changes on Num1 & Num2
}
@Override
protected Void doInBackground(Void... voids) {
//Use Num1 and Num2
}
}
Solution
When you are passing in the primitive variables into the async task consturctor, it is passed by value so any changes to num1 and num2 are not reflected on Num1 and Num2. So yes, it is fine unless
1) You create another thread inside the async task and modify Num1 and Num2 in that thread. Then you would have to declare them volatile and use some sort of locks to restrict access for the async task and the created thread.
2) You access and modify Num1 and Num2 in the main UI thread by calling AsynTaskObj.Num1 or AsyncTaskObj.Num2. Same situation as above.
I would declare Num1 and Num2 as private variables for encapsulation.
Answered By - Steven
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.