开发者

2 BroadcastReceivers and 1 static variable

开发者 https://www.devze.com 2023-02-06 04:07 出处:网络
I have 2 BroadcastReceivers in my开发者_JAVA百科 android application. They are in the same package.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消