I have 2 BroadcastReceivers in my开发者_JAVA百科 android application. They are in the same package. If in the onReceive() method, they both read/write a static class variable (in a separate Util class). Does android create 1 copy of that static class variable or 2 (1 for each receiver)?
And what do I need to do to make sure they are accessing the static class variable not corrupting the data?
There will only be one instance of the static variable. From http://download.oracle.com/javase/tutorial/java/javaOO/classvars.html:
A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.
To avoid problems, you will have to make sure the static variable is thread safe. Some data structures, like Vector
, are already thread safe, so you would not have to do anything further. Otherwise, you may have to use the synchronized keyword or something from the java.util.concurrent.locks package.
Don't use static variables, make the class Singleton.
"And what do I need to do to make sure they are accessing the static class variable not corrupting the data?" - add synchronized
to getters/setters
精彩评论