Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 listeners. However I am unsure how to implement it and also, I would like to stick with the Observer pattern implementation, if possible.

like image 598
Vort3x Avatar asked Sep 23 '11 13:09

Vort3x


1 Answers

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.

like image 137
Thomas Avatar answered Sep 28 '22 14:09

Thomas