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 listeners. 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 Observable
s - you'd need to add synchronization on that shared data yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With