开发者

Is java.util.Observable thread-safe?

In java's Observer pattern classes Observer and Observable, are calls made to Observable objects's notifyObservers(Object arg0), in different threads, thread-safe?

Example: I have multiple threads, all Observables, that will be calling notifyObservers(...) ever so often. All these threads report to a single Observer object.

Will I encounter concurrency issues, and what would be a better way to solve this? I am aware of a possible solution using event lis开发者_如何学编程teners. However I am unsure how to implement it and also, I would like to stick with the Observer pattern implementation, if possible.


From the source code (I have Java 5 source, but it should be the same for Java 6 and 7) it seems like you only have synchronization on the Observable itself.

From the notifyObservers(...) method (in Observable):

synchronized (this) {
  //the observers are notified in this block, with no additional synchronization
}

Thus if the Observer doesn't change any shared data it should be fine. If it does - you could have multiple calls to update(Observable, Object) with different Observables - you'd need to add synchronization on that shared data yourself.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜