Do I need to copy static objects if I want to access them from an AsyncTask?
-
28-09-2019 - |
문제
I have a project that uses AsyncTask
to get work done in background.
This project also uses a class as a generic holder for static values like database keys, but also for one or two useful objects for the whole project. Let's say this class is called public class Constants
.
I want to access one of these objects from an AsyncTask
, and I don't know if I need to copy it or not.
I am not actually getting errors or crashes, but I get some user feedback reporting crashes that I cannot reproduce, so I'm gessing I am doing something wrong with this.
My current processing is this:
onStart() {// somewhere in the UI thread
new MyTask(Constants.theObject).execute(); // (1)
}
// ...
class MyTask extends AsyncTask<...> {
MyObjectType object;
MyTask(MyObjectType theObjectInstance) {
object = theObjectInstance; // (2)
// ...
doInBackground() { // (3)
// ...
}
In (1)
, Constants.theObject
is a static object created at application startup
In (2)
, I get a reference to the existing static object Constants.theObject
In (3)
, we are no longer in the UI thread, and I want to access Constants.theObject
(which may also be being used in the main thread)
.
I think there are three possible cases.
- this code is ugly, I should do otherwise
- this code is OK, the user feedback is not about this
- this code is quite OK, but I should make a copy of
Constants.theObject
if I want to use it indoInBackground
; otherwise it can fail
I hope you can help me! Thanks a lot for reading.
해결책
From what you've written, I don't think you need to make a copy, unless MyObjectType
is NOT thread-safe, in which case, you need to ensure that only 1 thread at a time is modifying it/it's-non-thread-safe-methods. (Making a copy would indeed solve this, but if you can make a copy, is a global-static really what you should be using anyway?)
Are you 100% sure that 1 and 3 can only happen AFTER the object has been initialized?
다른 팁
It may be because more than one thread is trying to change the same object. it may cause unexpected results/complete failure. You may wanna use some lock so that no 2 threads can updates the object at the same time. This case it will slow down your asynch operations as they all depend on exact one intance. I guess you are using static object for a reason, you may want to consider it doing some other way if possible.