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
Observableitself.From the
notifyObservers(...)method (inObservable):Thus if the
Observerdoesn’t change any shared data it should be fine. If it does – you could have multiple calls toupdate(Observable, Object)with differentObservables – you’d need to add synchronization on that shared data yourself.